#!/usr/bin/env bash
# Register joiners in bulk from a CSV export of your HR system, and start their onboarding.
#
#   ELOS_API=https://<your ELOS API address> ELOS_KEY=esk.… ./import-joiners.sh joiners.csv
#
# CSV columns (header row required): name,role,team,manager,project
# For each row it registers the joiner (skipped if someone with that exact name exists),
# generates their knowledge journey, and requests the day-one access bundle for their role.
# The key needs a role with Manage people and Request access (Engineering Manager works).
# Safe to re-run: existing people are skipped and every write carries an Idempotency-Key.
set -euo pipefail

: "${ELOS_API:?set ELOS_API to your ELOS API address}"
: "${ELOS_KEY:?set ELOS_KEY to a service account API key}"
CSV="${1:?usage: import-joiners.sh joiners.csv}"
command -v jq >/dev/null || { echo "jq is required" >&2; exit 1; }

# call METHOD PATH [JSON] [IDEMPOTENCY-KEY]: retries on 429 using Retry-After.
call() {
  local method=$1 path=$2 body=${3:-} key=${4:-} out status
  for _ in 1 2 3 4 5; do
    out=$(curl -sS -w '\n%{http_code}' -X "$method" "$ELOS_API/v1$path" \
      -H "Authorization: Bearer $ELOS_KEY" -H "Content-Type: application/json" \
      ${key:+-H "Idempotency-Key: $key"} ${body:+--data "$body"})
    status=${out##*$'\n'}
    if [ "$status" = 429 ]; then sleep 2; continue; fi
    if [ "$status" -ge 400 ]; then echo "  $method $path failed ($status): ${out%$'\n'*}" >&2; return 1; fi
    printf '%s' "${out%$'\n'*}"
    return 0
  done
  echo "  $method $path: still rate limited" >&2; return 1
}

slug() { printf '%s' "$1" | tr '[:upper:]' '[:lower:]' | tr -cs 'a-z0-9' '-'; }

created=0 skipped=0 failed=0
while IFS=, read -r name role team manager project; do
  [ "$name" = "name" ] && continue           # header
  [ -z "$name" ] && continue
  q=$(jq -rn --arg v "$name" '$v|@uri')
  if call GET "/people?q=$q&stage=all&limit=50" | jq -e --arg n "$name" '.data[] | select(.name == $n)' >/dev/null; then
    echo "skip  $name (already in ELOS)"; skipped=$((skipped + 1)); continue
  fi
  id=$(slug "$name")
  body=$(jq -cn --arg name "$name" --arg role "$role" --arg team "$team" --arg manager "$manager" \
    '{name: $name, role: $role, team: $team} + (if $manager == "" then {} else {manager: $manager} end)')
  if ! person=$(call POST /people "$body" "joiner-$id"); then failed=$((failed + 1)); continue; fi
  pid=$(jq -r .id <<<"$person")
  call POST /journeys "$(jq -cn --arg p "$pid" --arg role "$role" --arg team "$team" --arg project "$project" \
    '{personId: $p, role: $role, team: $team, project: $project}')" "journey-$id" >/dev/null || true
  call POST /access/bundle "$(jq -cn --arg p "$pid" '{personId: $p}')" "bundle-$id" >/dev/null || true
  echo "added $name ($role, $team)"; created=$((created + 1))
done < "$CSV"

echo "done: $created added, $skipped skipped, $failed failed"
[ "$failed" -eq 0 ]
