#!/usr/bin/env bash
# easyscep-it: IT-side helper for the EasyScep Linux device kit.
# Requires bash, curl and jq. The API key comes from EASYSCEP_API_KEY or a
# hidden prompt; it is never taken from an argument and never printed.
set -euo pipefail

KIT_VERSION=0.1.1
PROFILE_DEFAULT=linux-devices

need_tools() {
  local t missing=()
  for t in curl jq openssl; do command -v "$t" >/dev/null 2>&1 || missing+=("$t"); done
  [ ${#missing[@]} = 0 ] || { echo "easyscep-it: missing: ${missing[*]} (on Ubuntu: sudo apt install ${missing[*]})" >&2; exit 2; }
}

die_usage() { echo "easyscep-it: $*" >&2; exit 2; }

usage() {
  cat <<'USAGE'
Usage:
  ./easyscep init                      once: answer a few questions, saved for later
  ./easyscep add NAME [--ssh USER@HOST]
                                       per laptop: writes easyscep-NAME.sh (run it on the
                                       laptop with sudo bash); --ssh does that for you
  ./easyscep revoke NAME               lost or retired laptop: revokes its certificates

Advanced:
  easyscep-it mint [--url U] [--profile P] [--expires PT2H]
                   [--channels scep|api|scep,api] [--var k=v]... [--out FILE] CN
  easyscep-it revoke [--url U] [--reason R] (--serial S | --token-id ID)
  easyscep-it site [--url U] [--profile P] [--scep-url U] [--ssid S] [--wired IFACE|auto]
                   --radius-ca FILE --radius-name N [--tls-ca FILE] [--device-script PATH] --out FILE
                   (without --scep-url, the SCEP URL is read from the profile;
                    --tls-ca only if the SCEP server's TLS certificate is not publicly trusted)

Environment:
  EASYSCEP_URL      base URL (default for --url)
  EASYSCEP_API_KEY  API key (prompted for, hidden, when unset on a terminal)
USAGE
}

WORK=""
cleanup() { [ -z "$WORK" ] || rm -rf "$WORK"; }
trap cleanup EXIT

# Create the private work dir and the header file holding the Authorization line.
init_auth() {
  if [ -z "${EASYSCEP_API_KEY:-}" ]; then
    if [ -t 0 ]; then
      read -rsp "EasyScep API key: " EASYSCEP_API_KEY; echo >&2
    else
      die_usage "EASYSCEP_API_KEY is not set and stdin is not a terminal"
    fi
  fi
  [ -n "$EASYSCEP_API_KEY" ] || die_usage "EASYSCEP_API_KEY is empty"
  WORK=$(mktemp -d)
  chmod 700 "$WORK"
  ( umask 077; printf 'Authorization: Bearer %s\n' "$EASYSCEP_API_KEY" >"$WORK/hdr" )
  chmod 600 "$WORK/hdr"
}

# api METHOD PATH [JSON]: prints the response body; exits 1 on HTTP status >= 400.
api() {
  local method=$1 path=$2 json=${3-} status
  local args=(-sS -o "$WORK/body" -w '%{http_code}' -H "@$WORK/hdr" -H 'Accept: application/json' -X "$method")
  if [ -n "$json" ]; then
    args+=(-H 'Content-Type: application/json' -d "$json")
  fi
  status=$(curl "${args[@]}" "$BASE_URL$path") || { echo "easyscep-it: request to $BASE_URL failed" >&2; exit 1; }
  if ! [[ "$status" =~ ^[0-9]+$ ]] || [ "$status" -ge 400 ]; then
    local title detail code
    title=$(jq -r '.title // empty' "$WORK/body" 2>/dev/null || true)
    detail=$(jq -r '.detail // empty' "$WORK/body" 2>/dev/null || true)
    code=$(jq -r '.code // empty' "$WORK/body" 2>/dev/null || true)
    echo "easyscep-it: API error (HTTP $status)" >&2
    [ -z "$title" ] || echo "  title:  $title" >&2
    [ -z "$detail" ] || echo "  detail: $detail" >&2
    [ -z "$code" ] || echo "  code:   $code" >&2
    exit 1
  fi
  cat "$WORK/body"
}

cmd_mint() {
  local profile=$PROFILE_DEFAULT expires=PT2H channels=scep out="" cn=""
  local -a vars=()
  BASE_URL=${EASYSCEP_URL:-}
  while [ $# -gt 0 ]; do
    case "$1" in
      --url)      [ $# -ge 2 ] || die_usage "--url needs a value"; BASE_URL=$2; shift 2 ;;
      --profile)  [ $# -ge 2 ] || die_usage "--profile needs a value"; profile=$2; shift 2 ;;
      --expires)  [ $# -ge 2 ] || die_usage "--expires needs a value"; expires=$2; shift 2 ;;
      --channels) [ $# -ge 2 ] || die_usage "--channels needs a value"; channels=$2; shift 2 ;;
      --var)      [ $# -ge 2 ] || die_usage "--var needs k=v"; vars+=("$2"); shift 2 ;;
      --out)      [ $# -ge 2 ] || die_usage "--out needs a file"; out=$2; shift 2 ;;
      -h|--help)  usage; exit 0 ;;
      -*)         die_usage "unknown option: $1" ;;
      *)          [ -z "$cn" ] || die_usage "unexpected argument: $1"; cn=$1; shift ;;
    esac
  done
  [ -n "$cn" ] || die_usage "mint needs a CN"
  [ -n "$BASE_URL" ] || die_usage "no URL: pass --url or set EASYSCEP_URL"
  BASE_URL=${BASE_URL%/}
  case "$channels" in scep|api|scep,api|api,scep) ;; *) die_usage "--channels must be scep, api or scep,api" ;; esac
  local kv
  for kv in "${vars[@]+"${vars[@]}"}"; do
    case "$kv" in ?*=*) ;; *) die_usage "--var needs k=v, got: $kv" ;; esac
  done

  init_auth

  local body="" k v
  body=$(jq -nc --arg expires "$expires" --arg channels "$channels" --arg cn "$cn" \
    '{expiresIn: $expires, channels: ($channels | split(",")), variables: {cn: $cn}}')
  for kv in "${vars[@]+"${vars[@]}"}"; do
    k=${kv%%=*}; v=${kv#*=}
    body=$(jq -c --arg k "$k" --arg v "$v" '.variables[$k] = $v' <<<"$body")
  done

  local resp token
  resp=$(api POST "/api/v1/profiles/$profile/enrollment-tokens" "$body")
  token=$(jq -er '.token' <<<"$resp") || { echo "easyscep-it: response has no token" >&2; exit 1; }

  jq -r '"id:        \(.id // "")\nexpiresAt: \(.expiresAt // "")\nscepUrl:   \(.scepUrl // "")"' <<<"$resp" >&2
  if [ -n "$out" ]; then
    ( umask 077; printf '%s\n' "$token" >"$out" )
    chmod 600 "$out"
  else
    printf '%s\n' "$token"
  fi
}

# revoke NAME: revoke every active certificate of that laptop (its current
# one, renewals and leftovers from re-runs), found by name in the profile.
cmd_revoke_name() {
  local name=$1; shift
  local reason=cessationOfOperation
  while [ $# -gt 0 ]; do
    case "$1" in
      --reason) [ $# -ge 2 ] || die_usage "--reason needs a value"; reason=$2; shift 2 ;;
      *) die_usage "unexpected argument: $1" ;;
    esac
  done
  [[ $name =~ ^[a-z0-9-]{1,63}$ ]] || die_usage "invalid laptop name '$name'"
  load_config
  BASE_URL=${EASYSCEP_URL%/}
  init_auth

  local serials="" page cursor="" q
  while :; do
    q="profile=$(jq -rn --arg v "$CFG_PROFILE" '$v|@uri')&status=active&limit=200"
    [ -z "$cursor" ] || q+="&cursor=$(jq -rn --arg v "$cursor" '$v|@uri')"
    page=$(api GET "/api/v1/certificates?$q")
    serials+=$(jq -r --arg n "$name" \
      '.items[] | select((.subject // "") | test("(^|,\\s*)CN=" + $n + "(,|$)")) | .serial' <<<"$page")$'\n'
    cursor=$(jq -r '.nextCursor // empty' <<<"$page")
    [ -n "$cursor" ] || break
  done
  serials=$(grep -v '^$' <<<"$serials" || true)
  [ -n "$serials" ] || { echo "easyscep: no active certificate for $name (profile $CFG_PROFILE)" >&2; exit 1; }

  local s body; body=$(jq -nc --arg r "$reason" '{reason: $r}')
  while IFS= read -r s; do
    case "$s" in *[!0-9A-Fa-f:]*) echo "easyscep: skipping invalid serial '$s'" >&2; continue ;; esac
    api POST "/api/v1/certificates/$s/revoke" "$body" >/dev/null
    echo "Revoked $s ($name)"
  done <<<"$serials"
  echo "$name can no longer connect once EasyRadius sees the revocation."
}

cmd_revoke() {
  if [ $# -gt 0 ] && [[ $1 != -* ]]; then cmd_revoke_name "$@"; return; fi
  local reason=cessationOfOperation serial="" token_id=""
  BASE_URL=${EASYSCEP_URL:-}
  while [ $# -gt 0 ]; do
    case "$1" in
      --url)      [ $# -ge 2 ] || die_usage "--url needs a value"; BASE_URL=$2; shift 2 ;;
      --reason)   [ $# -ge 2 ] || die_usage "--reason needs a value"; reason=$2; shift 2 ;;
      --serial)   [ $# -ge 2 ] || die_usage "--serial needs a value"; serial=$2; shift 2 ;;
      --token-id) [ $# -ge 2 ] || die_usage "--token-id needs a value"; token_id=$2; shift 2 ;;
      -h|--help)  usage; exit 0 ;;
      -*)         die_usage "unknown option: $1" ;;
      *)          die_usage "unexpected argument: $1" ;;
    esac
  done
  if [ -n "$serial" ] && [ -n "$token_id" ]; then die_usage "pass only one of --serial and --token-id"; fi
  [ -n "$serial$token_id" ] || die_usage "revoke needs --serial or --token-id"
  [ -n "$BASE_URL" ] || die_usage "no URL: pass --url or set EASYSCEP_URL"
  BASE_URL=${BASE_URL%/}
  case "$serial" in *[!0-9A-Fa-f:]*) die_usage "--serial must be hex (0-9, A-F, optional colons)" ;; esac
  case "$token_id" in *[!A-Za-z0-9._-]*) die_usage "--token-id has invalid characters" ;; esac

  init_auth

  if [ -n "$token_id" ]; then
    local tok status
    tok=$(api GET "/api/v1/enrollment-tokens/$token_id")
    status=$(jq -r '.status // empty' <<<"$tok")
    if [ "$status" != consumed ]; then
      case "$status" in
        active)  echo "easyscep-it: token $token_id has not been used, so no certificate was issued; revoke the token in the portal instead" >&2 ;;
        in_use)  echo "easyscep-it: token $token_id is in use (status in_use); no certificate has been issued yet. Wait for enrollment to finish, or revoke the token in the portal" >&2 ;;
        *)       echo "easyscep-it: token $token_id has status '${status:-unknown}', not consumed; there is no certificate to revoke from it" >&2 ;;
      esac
      exit 1
    fi
    serial=$(jq -r '.certificateSerial // empty' <<<"$tok")
    [ -n "$serial" ] || { echo "easyscep-it: token $token_id is consumed but reports no certificateSerial" >&2; exit 1; }
    case "$serial" in *[!0-9A-Fa-f:]*) echo "easyscep-it: token $token_id reports an invalid certificateSerial" >&2; exit 1 ;; esac
  fi

  local body resp
  body=$(jq -nc --arg r "$reason" '{reason: $r}')
  resp=$(api POST "/api/v1/certificates/$serial/revoke" "$body")
  jq -r --arg s "$serial" --arg r "$reason" \
    '"Revoked \(.serial // $s) (\(.reason // $r)) at \(.revokedAt // "unknown time")"' <<<"$resp"
}

# check_ca_file FLAG FILE: a readable PEM certificate without a private key
# (it is embedded in the setup file that goes on every laptop).
check_ca_file() {
  [ -r "$2" ] && openssl x509 -in "$2" -noout 2>/dev/null || die_usage "$1 $2 is not a readable PEM certificate"
  ! grep -q 'PRIVATE KEY' "$2" \
    || die_usage "$1 $2 contains a private key; give a file with only the CA certificate (it is embedded in the setup file)"
}

# site: write a self-contained device script with the site settings and the
# RADIUS CA embedded between the "# >>> site" / "# <<< site" markers.
cmd_site() {
  local scep_url="" ssid="" wired="" ca="" tls_ca="" radius_name="" out="" script profile=$PROFILE_DEFAULT
  script="$(dirname "$0")/../device/easyscep"
  BASE_URL=${EASYSCEP_URL:-}
  while [ $# -gt 0 ]; do
    case "$1" in
      -h|--help) usage; exit 0 ;;
      --scep-url|--ssid|--wired|--radius-ca|--tls-ca|--radius-name|--device-script|--out|--url|--profile)
        [ $# -ge 2 ] || die_usage "$1 needs a value" ;;
    esac
    case "$1" in
      --scep-url)      scep_url=$2 ;;
      --tls-ca)        tls_ca=$2 ;;
      --url)           BASE_URL=$2 ;;
      --profile)       profile=$2 ;;
      --ssid)          [ -z "$ssid" ] || die_usage "--ssid may be given only once"; ssid=$2 ;;
      --wired)         [ -z "$wired" ] || die_usage "--wired may be given only once"; wired=$2 ;;
      --radius-ca)     ca=$2 ;;
      --radius-name)   radius_name=$2 ;;
      --device-script) script=$2 ;;
      --out)           out=$2 ;;
      -*)              die_usage "unknown option: $1" ;;
      *)               die_usage "unexpected argument: $1" ;;
    esac
    shift 2
  done
  [ -n "$scep_url" ] || [ -n "$BASE_URL" ] \
    || die_usage "site needs --scep-url, or --url / EASYSCEP_URL to read it from the profile"
  [ -n "$ssid" ] || [ -n "$wired" ] || die_usage "site needs --ssid and/or --wired"
  [ -n "$ca" ] || die_usage "site needs --radius-ca FILE"
  [ -n "$radius_name" ] || die_usage "site needs --radius-name"
  [ -n "$out" ] || die_usage "site needs --out FILE"
  check_ca_file --radius-ca "$ca"
  [ -z "$tls_ca" ] || check_ca_file --tls-ca "$tls_ca"
  [ -r "$script" ] || { echo "easyscep-it: cannot read device script $script" >&2; exit 1; }
  local starts ends
  starts=$(grep -cx '# >>> site' "$script" || true)
  ends=$(grep -cx '# <<< site' "$script" || true)
  if [ "$starts" != 1 ] || [ "$ends" != 1 ]; then
    echo "easyscep-it: $script must contain exactly one '# >>> site' and one '# <<< site' line" >&2
    exit 1
  fi

  if [ -z "$scep_url" ]; then
    BASE_URL=${BASE_URL%/}
    init_auth
    local prof
    prof=$(api GET "/api/v1/profiles/$profile")
    scep_url=$(jq -r '.scepUrl // empty' <<<"$prof" 2>/dev/null || true)
    [ -n "$scep_url" ] || { echo "easyscep-it: profile $profile has no scepUrl; pass --scep-url" >&2; exit 1; }
    echo "easyscep-it: SCEP URL from profile $profile: $scep_url" >&2
  fi

  write_setup "$out" "$script" "$scep_url" "$ssid" "$wired" "$radius_name" "$ca" "$tls_ca" "$profile" "" ""
  echo "easyscep-it: wrote $out (run it on each laptop with: sudo ./$(basename "$out"))" >&2
}

# write_setup OUT TEMPLATE SCEP_URL SSID WIRED RADIUS_NAME RADIUS_CA TLS_CA PROFILE CN TOKEN
# Copy the device template with the settings between the "# >>> site" /
# "# <<< site" markers. With a TOKEN the file is a one-time secret (mode 600).
write_setup() {
  local out=$1 script=$2 scep_url=$3 ssid=$4 wired=$5 radius_name=$6 ca=$7 tls_ca=$8 profile=$9 cn=${10} token=${11}
  local starts ends
  starts=$(grep -cx '# >>> site' "$script" || true)
  ends=$(grep -cx '# <<< site' "$script" || true)
  if [ "$starts" != 1 ] || [ "$ends" != 1 ]; then
    echo "easyscep-it: $script must contain exactly one '# >>> site' and one '# <<< site' line" >&2
    exit 1
  fi
  local b64 tls_b64="" block note="contains no secrets"
  b64=$(openssl base64 -A -in "$ca")
  [ -z "$tls_ca" ] || tls_b64=$(openssl base64 -A -in "$tls_ca")
  block=$(printf 'SITE_SCEP_URL=%q\nSITE_SSID=%q\nSITE_WIRED=%q\nSITE_RADIUS_NAME=%q\nSITE_RADIUS_CA_B64=%q\nSITE_TLS_CA_B64=%q\nSITE_PROFILE=%q\nSITE_CN=%q\nSITE_TOKEN=%q\n' \
    "$scep_url" "$ssid" "$wired" "$radius_name" "$b64" "$tls_b64" "$profile" "$cn" "$token")
  [ -z "$token" ] || note="contains a ONE-TIME TOKEN: one use, deletes itself when run"

  local tmp line first=1 inblock=0
  tmp=$(mktemp "$(dirname "$out")/.easyscep-site.XXXXXX") || { echo "easyscep-it: cannot write next to $out" >&2; exit 1; }
  chmod 600 "$tmp"
  {
    while IFS= read -r line || [ -n "$line" ]; do
      if [ "$inblock" = 1 ]; then
        [ "$line" = '# <<< site' ] || continue
        inblock=0
      fi
      printf '%s\n' "$line"
      if [ "$first" = 1 ]; then
        first=0
        printf '# Generated by easyscep-it %s site on %s — %s\n' "$KIT_VERSION" "$(date -u +%Y-%m-%d)" "$note"
      elif [ "$line" = '# >>> site' ]; then
        printf '%s\n' "$block"
        inblock=1
      fi
    done <"$script"
  } >"$tmp" || { rm -f "$tmp"; exit 1; }
  [ -n "$token" ] || chmod 755 "$tmp"
  mv -f "$tmp" "$out"
}

CONFIG=${EASYSCEP_CONFIG:-${XDG_CONFIG_HOME:-$HOME/.config}/easyscep/config}

# Read the settings saved by init. Environment variables still win.
load_config() {
  [ -r "$CONFIG" ] || die_usage "not set up yet: run ./easyscep init first"
  # shellcheck source=/dev/null
  . "$CONFIG"
  EASYSCEP_URL=${EASYSCEP_URL:-$CFG_URL}
  EASYSCEP_API_KEY=${EASYSCEP_API_KEY:-$CFG_API_KEY}
}

# ask VAR PROMPT [DEFAULT]: read an answer from stdin.
ask() {
  local _a=""
  read -r -p "$2${3:+ [$3]}: " _a || true
  printf -v "$1" '%s' "${_a:-${3:-}}"
}

# fetch_scep_ca SCEP_URL OUT: the CA certificates of an EasyScep profile, via
# SCEP GetCACert (public, no API key). The answer is one DER certificate or a
# PKCS#7 bundle that may also hold an RA certificate; keep only CA certificates.
# When EasyRadius is linked to EasyScep, its server certificate is issued by
# this CA, so this is the RADIUS CA.
fetch_scep_ca() {
  local url=$1 out=$2 raw=$WORK/getcacert all=$WORK/getcacert.pem
  local sep='?'; [[ $url != *\?* ]] || sep='&'
  curl -fsS -o "$raw" "$url${sep}operation=GetCACert" \
    || { echo "easyscep: could not download the CA certificate from $url" >&2; exit 1; }
  openssl pkcs7 -inform DER -in "$raw" -print_certs -out "$all" 2>/dev/null \
    || openssl x509 -inform DER -in "$raw" -out "$all" 2>/dev/null \
    || openssl x509 -in "$raw" -out "$all" 2>/dev/null \
    || { echo "easyscep: $url did not return a CA certificate" >&2; exit 1; }
  : >"$out"
  local pem="" line
  while IFS= read -r line; do
    pem+=$line$'\n'
    if [ "$line" = "-----END CERTIFICATE-----" ]; then
      if openssl x509 -noout -ext basicConstraints <<<"$pem" 2>/dev/null | grep -q 'CA:TRUE'; then
        printf '%s' "$pem" >>"$out"
      fi
      pem=""
    elif [ "$line" = "-----BEGIN CERTIFICATE-----" ]; then
      pem=$line$'\n'
    fi
  done <"$all"
  [ -s "$out" ] || { echo "easyscep: $url returned no CA certificate" >&2; exit 1; }
}

# init: ask the few site questions once, check them against EasyScep, save them.
cmd_init() {
  local url=${EASYSCEP_URL:-} key=${EASYSCEP_API_KEY:-} profile="" ssid="" wired="" ca="" rname="" tls_ca="" net_given=0
  while [ $# -gt 0 ]; do
    case "$1" in
      --url|--profile|--ssid|--wired|--radius-ca|--radius-name|--tls-ca) [ $# -ge 2 ] || die_usage "$1 needs a value" ;;
      -h|--help) usage; exit 0 ;;
      *) die_usage "unknown option: $1" ;;
    esac
    case "$1" in
      --url) url=$2 ;; --profile) profile=$2 ;; --radius-ca) ca=$2 ;;
      --radius-name) rname=$2 ;; --tls-ca) tls_ca=$2 ;;
      --ssid) ssid=$2; net_given=1 ;; --wired) wired=$2; net_given=1 ;;
    esac
    shift 2
  done
  [ -n "$url" ] || ask url "EasyScep address (https://...)"
  if [ -z "$key" ]; then read -rs -p "API key: " key || true; echo >&2; fi
  [ -n "$profile" ] || ask profile "Profile" "$PROFILE_DEFAULT"
  if [ "$net_given" = 0 ]; then
    local yn; ask yn "Use wired 802.1X (y/n)" y
    case "${yn,,}" in y*) wired=auto ;; esac
    ask ssid "Wi-Fi network name (empty for none)"
  fi
  local fetch_ca=0
  if [ -z "$ca" ]; then
    local linked; ask linked "EasyRadius gets its certificate from EasyScep (y/n)" y
    case "${linked,,}" in
      n*) ask ca "RADIUS server's CA certificate file" ;;
      *) fetch_ca=1 ;;
    esac
  fi
  [ -n "$rname" ] || ask rname "RADIUS server name (as in its certificate)"

  [ -n "$url" ] || die_usage "no EasyScep address"
  # The API is HTTPS only: accept "host", "http://host" and "https://host".
  url=${url#http://}; url=https://${url#https://}
  [ -n "$key" ] || die_usage "no API key"
  [ -n "$ssid" ] || [ -n "$wired" ] || die_usage "choose wired and/or a Wi-Fi network"
  [ -n "$rname" ] || die_usage "no RADIUS server name"
  [ "$fetch_ca" = 1 ] || check_ca_file "RADIUS CA" "$ca"
  [ -z "$tls_ca" ] || check_ca_file --tls-ca "$tls_ca"

  BASE_URL=${url%/} EASYSCEP_API_KEY=$key
  init_auth
  local prof scep_url
  prof=$(api GET "/api/v1/profiles/$profile")
  scep_url=$(jq -r '.scepUrl // empty' <<<"$prof" 2>/dev/null || true)
  [ -n "$scep_url" ] || { echo "easyscep: profile $profile reports no SCEP URL" >&2; exit 1; }
  if [ "$fetch_ca" = 1 ]; then
    ca=$WORK/easyscep-ca.pem
    fetch_scep_ca "$scep_url" "$ca"
    echo "RADIUS CA from EasyScep: $(openssl x509 -in "$ca" -noout -subject | sed 's/^subject= *//')"
  fi

  local dir; dir=$(dirname "$CONFIG")
  mkdir -p "$dir"; chmod 700 "$dir"
  cat "$ca" >"$dir/radius-ca.pem"
  local tls_saved=""
  if [ -n "$tls_ca" ]; then cat "$tls_ca" >"$dir/tls-ca.pem"; tls_saved=$dir/tls-ca.pem; fi
  ( umask 077
    printf 'CFG_URL=%q\nCFG_API_KEY=%q\nCFG_PROFILE=%q\nCFG_SCEP_URL=%q\nCFG_SSID=%q\nCFG_WIRED=%q\nCFG_RADIUS_NAME=%q\nCFG_RADIUS_CA=%q\nCFG_TLS_CA=%q\n' \
      "$BASE_URL" "$key" "$profile" "$scep_url" "$ssid" "$wired" "$rname" "$dir/radius-ca.pem" "$tls_saved" >"$CONFIG" )
  chmod 600 "$CONFIG"
  echo "Saved (profile $profile, $scep_url)."
  echo "Next, for each laptop:  ./easyscep add <laptop-name>"
}

# add NAME [--ssh USER@HOST]: mint a token and write one file that sets the
# laptop up with nothing to paste; with --ssh, also copy it there and run it.
cmd_add() {
  local name="" ssh="" out=""
  while [ $# -gt 0 ]; do
    case "$1" in
      --ssh) [ $# -ge 2 ] || die_usage "--ssh needs USER@HOST"; ssh=$2; shift 2 ;;
      --out) [ $# -ge 2 ] || die_usage "--out needs a file"; out=$2; shift 2 ;;
      -h|--help) usage; exit 0 ;;
      -*) die_usage "unknown option: $1" ;;
      *) [ -z "$name" ] || die_usage "unexpected argument: $1"; name=$1; shift ;;
    esac
  done
  [ -n "$name" ] || die_usage "add needs the laptop's name, e.g.: ./easyscep add laptop-001"
  [[ $name =~ ^[a-z0-9-]{1,63}$ ]] || die_usage "invalid laptop name '$name' (lowercase letters, digits and -)"
  load_config
  [ -n "$out" ] || out=./easyscep-$name.sh
  BASE_URL=${EASYSCEP_URL%/}
  init_auth

  local body resp token id expires
  body=$(jq -nc --arg cn "$name" '{expiresIn: "PT2H", channels: ["scep"], variables: {cn: $cn}}')
  resp=$(api POST "/api/v1/profiles/$CFG_PROFILE/enrollment-tokens" "$body")
  token=$(jq -er '.token' <<<"$resp") || { echo "easyscep: response has no token" >&2; exit 1; }
  id=$(jq -r '.id // ""' <<<"$resp"); expires=$(jq -r '.expiresAt // ""' <<<"$resp")

  write_setup "$out" "$(dirname "$0")/../device/easyscep" "$CFG_SCEP_URL" "$CFG_SSID" "$CFG_WIRED" \
    "$CFG_RADIUS_NAME" "$CFG_RADIUS_CA" "$CFG_TLS_CA" "$CFG_PROFILE" "$name" "$token"
  token=""

  if [ -z "$ssh" ]; then
    echo "Wrote $out for $name (token $id, valid until $expires, one use)."
    echo "Copy it to the laptop and run:  sudo bash $(basename "$out")"
    return 0
  fi
  local remote=easyscep-$name.sh rc=0
  echo "Setting up $name on $ssh (sudo may ask for the password)..."
  if scp -q "$out" "$ssh:$remote"; then
    ssh -t "$ssh" "sudo bash ./$remote" || rc=$?
  else
    rc=$?
  fi
  rm -f "$out"
  [ "$rc" = 0 ] || { echo "easyscep: setup on $ssh failed (exit $rc); fix it and run add again (it mints a new token)" >&2; exit 1; }
}

[ $# -gt 0 ] || { usage >&2; exit 2; }
sub=$1; shift
case "$sub" in
  --version|version) echo "easyscep-it $KIT_VERSION"; exit 0 ;;
  mint|site|revoke|init|add) need_tools ;;
esac
case "$sub" in
  init) cmd_init "$@" ;;
  add) cmd_add "$@" ;;
  mint) cmd_mint "$@" ;;
  site) cmd_site "$@" ;;
  revoke) cmd_revoke "$@" ;;
  -h|--help|help) usage ;;
  *) die_usage "unknown command: $sub" ;;
esac
