#!/usr/bin/env bash
# easyscep: enroll this Ubuntu laptop with an EasyScep device certificate.
#   easyscep [setup|status|remove|renewed] [flags]      (setup is the default)
# setup (root): enrolls via certmonger over SCEP using a single-use token as
# the challenge password. The token only ever travels as a 600 file (-l).
set -euo pipefail

# >>> site
SITE_SCEP_URL=''
SITE_SSID=''
SITE_WIRED=''
SITE_RADIUS_NAME=''
SITE_RADIUS_CA_B64=''
SITE_TLS_CA_B64=''
SITE_PROFILE=''
SITE_CN=''
SITE_TOKEN=''
# <<< site

KIT_VERSION=0.1.1
ES_ROOT=${ES_ROOT:-}
ES_DIR=$ES_ROOT/etc/easyscep
CM_CONF=$ES_ROOT/etc/certmonger/certmonger.conf
CM_REQS=$ES_ROOT/var/lib/certmonger/requests
SYSTEM_TLS_BUNDLE=$ES_ROOT/etc/ssl/certs/ca-certificates.crt
CA_NICK=easyscep
REQ_ID=easyscep-device
KIT_CONNS=(easyscep-wifi easyscep-wired)
WORK=""
net_err=""

die()   { echo "easyscep: $*" >&2; exit 1; }
usage() { echo "easyscep: $*" >&2; exit 2; }

cleanup() { [ -z "$WORK" ] || rm -rf "$WORK"; }
trap cleanup EXIT
trap 'exit 130' INT
trap 'exit 143' TERM

normalize_cn() {
  local n=${1,,}
  n=${n%%.*}
  [[ $n =~ ^[a-z0-9-]{1,63}$ ]] || usage "invalid name '$1' (need [a-z0-9-], 1-63 chars)"
  printf '%s' "$n"
}

# check_ca_file LABEL FILE: a PEM certificate without a private key, or exit 2.
check_ca_file() {
  openssl x509 -in "$2" -noout 2>/dev/null || usage "$1 $2 is not a PEM certificate"
  ! grep -q 'PRIVATE KEY' "$2" || usage "$1 $2 contains a private key; give a file with only the CA certificate"
}

# The command that mints a new token for this laptop, for retry hints.
mint_hint() { echo "easyscep-it mint${SITE_PROFILE:+ --profile $SITE_PROFILE} $cn"; }

check_root() {
  [ "${ES_ALLOW_NONROOT:-}" = 1 ] || [ "$(id -u)" = 0 ] || usage "run as root (sudo)"
}

parse_args() {
  scep_url=$SITE_SCEP_URL ssid=$SITE_SSID wired=$SITE_WIRED radius_name=$SITE_RADIUS_NAME
  radius_ca="" tls_ca="" cn=$SITE_CN token_file="" key_size=3072 token_id=unknown
  while [ $# -gt 0 ]; do
    case "$1" in
      -h|--help) echo "usage: easyscep setup [--scep-url URL] [--ssid S] [--wired IFACE|auto] [--radius-name N] [--radius-ca FILE] [--tls-ca FILE] [--cn NAME] [--token-file FILE] [--key-size N]"; exit 0 ;;
      --scep-url|--ssid|--wired|--radius-name|--radius-ca|--tls-ca|--cn|--token-file|--key-size)
        [ $# -ge 2 ] || usage "$1 needs a value" ;;
    esac
    case "$1" in
      --scep-url) scep_url=$2 ;;
      --ssid) ssid=$2 ;;
      --wired) wired=$2 ;;
      --radius-name) radius_name=$2 ;;
      --radius-ca) radius_ca=$2 ;;
      --tls-ca) tls_ca=$2 ;;
      --cn) cn=$2 ;;
      --token-file) token_file=$2 ;;
      --key-size) key_size=$2 ;;
      *) usage "unknown option: $1" ;;
    esac
    shift 2
  done
}

# Validate everything up front (exit 2) so we never enroll and then fail on
# missing network settings.
validate() {
  [ -n "$cn" ] || cn=$(hostname)
  cn=$(normalize_cn "$cn")
  [ -n "$scep_url" ] || usage "missing --scep-url (and no site default)"
  [ -n "$ssid" ] || [ -n "$wired" ] || usage "need --ssid and/or --wired (and no site default)"
  [ -n "$radius_name" ] || usage "missing --radius-name (and no site default)"
  if [ -z "$radius_ca" ]; then
    [ -n "$SITE_RADIUS_CA_B64" ] || usage "missing --radius-ca (and no site default)"
    radius_ca=$WORK/radius-ca.pem
    printf '%s' "$SITE_RADIUS_CA_B64" | base64 -d >"$radius_ca" 2>/dev/null || usage "the site RADIUS CA is not valid base64"
  fi
  check_ca_file "RADIUS CA" "$radius_ca"
  # HTTPS SCEP: certmonger needs a CA file (-R) to check the server's TLS
  # certificate. Embedded/--tls-ca for private TLS CAs, else the system bundle.
  tls_ca_src=""
  if [[ ${scep_url,,} == https://* ]]; then
    if [ -n "$tls_ca" ]; then
      tls_ca_src=$tls_ca
    elif [ -n "$SITE_TLS_CA_B64" ]; then
      tls_ca_src=$WORK/tls-ca.pem
      printf '%s' "$SITE_TLS_CA_B64" | base64 -d >"$tls_ca_src" 2>/dev/null || usage "the site TLS CA is not valid base64"
    fi
    if [ -n "$tls_ca_src" ]; then
      check_ca_file "TLS CA" "$tls_ca_src"
      tls_ca=$ES_DIR/scep-tls-ca.pem
    else
      [ -s "$SYSTEM_TLS_BUNDLE" ] \
        || usage "no system CA bundle at $SYSTEM_TLS_BUNDLE; install it (sudo apt-get install ca-certificates) or pass --tls-ca FILE"
      tls_ca=$SYSTEM_TLS_BUNDLE
    fi
  else
    tls_ca=""
  fi
  [[ $key_size =~ ^[0-9]+$ ]] || usage "--key-size must be a number"
  if [ -n "$token_file" ] && [ -e "$token_file" ]; then
    local mode; mode=$(stat -L -c %a "$token_file" 2>/dev/null) || usage "cannot stat --token-file $token_file"
    (( (8#$mode & 8#077) == 0 )) \
      || usage "--token-file $token_file is readable by group or others (mode $mode); run: chmod 600 $token_file"
  fi
}

ensure_certmonger() {
  if ! command -v getcert >/dev/null 2>&1; then
    local hint="certmonger is in Ubuntu's universe repository: enable it (sudo add-apt-repository universe), check the laptop is online, then run setup again"
    echo "installing certmonger..." >&2
    apt-get update >&2 || echo "easyscep: warning: apt-get update failed; trying the install anyway" >&2
    apt-get install -y certmonger >&2 || die "could not install certmonger. $hint"
    command -v getcert >/dev/null 2>&1 || die "certmonger install failed (no getcert). $hint"
  fi
  mkdir -p "$(dirname "$CM_CONF")"
  [ -e "$CM_CONF" ] || : >"$CM_CONF"
  local tmp; tmp=$(mktemp "$WORK/conf.XXXXXX")
  # In [defaults], set (once, replacing any old value):
  # - challenge_password_otp = yes: certmonger doesn't keep the token;
  # - max_key_use_count = 1: every renewal uses a NEW key. EasyScep profiles
  #   can require a new key on renewal ("The renewed certificate must have a
  #   new key"); without this, certmonger's automatic renewals reuse the key
  #   and are refused.
  awk -v settings="challenge_password_otp=yes;max_key_use_count=1" '
    BEGIN { n = split(settings, kv, ";"); for (i = 1; i <= n; i++) { split(kv[i], p, "="); key[i] = p[1]; val[i] = p[2] } }
    function flush(   i) { if (indef) for (i = 1; i <= n; i++) if (!done[i]) { print key[i] " = " val[i]; done[i] = 1 } }
    /^\[/ { flush(); indef = ($0 ~ /^\[defaults\][ \t]*$/); if (indef) seen = 1; print; next }
    indef { for (i = 1; i <= n; i++) if ($0 ~ "^[ \t]*" key[i] "[ \t]*=") { if (!done[i]) { print key[i] " = " val[i]; done[i] = 1 }; next } }
    { print }
    END { if (!seen) print "[defaults]"; indef = 1; flush() }
  ' "$CM_CONF" >"$tmp"
  cat "$tmp" >"$CM_CONF"
  systemctl restart certmonger
}

# get_token DEST: write the trimmed token to DEST (mode 600), from --token-file
# or a hidden prompt on the terminal (ES_TTY overrides /dev/tty for tests).
trim() { local t=${1#"${1%%[![:space:]]*}"}; printf '%s' "${t%"${t##*[![:space:]]}"}"; }

# Why $1 is not an enrollment token, or nothing if it is one. Tokens are
# {8-char id}.{23-char secret}; EasyScep refuses any other challenge as a token,
# so a bad paste is caught here, before it is sent (the token stays unused).
token_problem() {
  [[ $1 =~ ^[A-Za-z0-9]{8}\.[A-Za-z0-9]{23}$ ]] && return 0
  if [ "${#1}" = 64 ]; then echo "it is 64 characters, a token is 32 (pasted twice?)"
  elif [ "${#1}" != 32 ]; then echo "it is ${#1} characters, a token is 32"
  else echo "a token is 8 letters/digits, a dot, then 23 letters/digits"; fi
}

get_token() {
  local dest=$1 tok why
  if [ -n "$token_file" ]; then
    [ -r "$token_file" ] || usage "cannot read --token-file $token_file"
    tok=$(trim "$(cat "$token_file")")
    [ -n "$tok" ] || usage "no token (empty)"
    why=$(token_problem "$tok")
    [ -z "$why" ] || usage "--token-file $token_file does not hold an enrollment token: $why"
    rm -f "$token_file"
  elif [ -n "$SITE_TOKEN" ]; then
    # A file from `easyscep add`: the token is inside. Delete the file now
    # that the token is read (a copy without it is installed later).
    tok=$(trim "$SITE_TOKEN")
    why=$(token_problem "$tok")
    [ -z "$why" ] || usage "the token in this file is damaged ($why); make a new file with: easyscep add $cn"
    if [ -f "${BASH_SOURCE[0]:-}" ]; then
      rm -f "${BASH_SOURCE[0]}" && echo "this file held a one-time token and has been deleted" >&2
    fi
  else
    local tty=${ES_TTY:-/dev/tty} tries=0
    [ -r "$tty" ] || usage "no token: cannot read from $tty; use --token-file FILE"
    exec 3<"$tty"
    while :; do
      tok=""
      read -rs -u 3 -p "Enrollment token (paste once, then Enter): " tok || true
      echo >&2
      tok=$(trim "$tok")
      [ -n "$tok" ] || usage "no token (empty)"
      why=$(token_problem "$tok")
      [ -n "$why" ] || break
      tries=$((tries + 1))
      (( tries < 3 )) || usage "that is not an enrollment token: $why. Nothing was sent; the token is still unused"
      echo "easyscep: that is not an enrollment token: $why. Try again." >&2
    done
    exec 3<&-
  fi
  token_id=${tok%%.*}   # the id is not secret; it names the token in the portal
  echo "token received (id $token_id)" >&2
  (umask 077; printf '%s' "$tok" >"$dest")
  chmod 600 "$dest"
}

RENEW_HOOK="/usr/local/sbin/easyscep renewed"
KIT_FILES=(device.key device.crt ca.pem)

# Move the current key, certificate and chain aside (*.old). certmonger, given
# a -f that already holds a valid certificate for the -k key, goes straight to
# MONITORING without contacting the CA, so the new token would never be used.
backup_previous() {
  local f
  for f in "${KIT_FILES[@]}"; do
    [ ! -e "$ES_DIR/$f" ] || mv -f "$ES_DIR/$f" "$ES_DIR/$f.old"
  done
}

discard_previous() {
  local f
  for f in "${KIT_FILES[@]}"; do rm -f "$ES_DIR/$f.old"; done
}

# Put the previous key and certificate back and track them again so they keep
# renewing. Returns 1 (and discards any partial backup) if there is no pair.
restore_previous() {
  local f
  if [ ! -e "$ES_DIR/device.key.old" ] || [ ! -e "$ES_DIR/device.crt.old" ]; then
    discard_previous; return 1
  fi
  for f in "${KIT_FILES[@]}"; do
    if [ -e "$ES_DIR/$f.old" ]; then mv -f "$ES_DIR/$f.old" "$ES_DIR/$f"; else rm -f "$ES_DIR/$f"; fi
  done
  local cafile=()
  [ ! -e "$ES_DIR/ca.pem" ] || cafile=(-F "$ES_DIR/ca.pem")
  getcert start-tracking -c "$CA_NICK" -I "$REQ_ID" -k "$ES_DIR/device.key" -f "$ES_DIR/device.crt" \
    "${cafile[@]+"${cafile[@]}"}" -m 0600 -M 0644 -C "$RENEW_HOOK" >/dev/null 2>&1 \
    || echo "easyscep: warning: could not track the previous certificate again; it will not renew by itself" >&2
  return 0
}

enroll_fail() {
  local step=$1 err=${2:-}
  getcert stop-tracking -i "$REQ_ID" >/dev/null 2>&1 || true
  echo "easyscep: enrollment failed at: $step" >&2
  [ -z "$err" ] || echo "easyscep: CA said: $err" >&2
  if [[ $step == *CA_REJECTED* ]]; then
    # SCEP only carries a generic failInfo; the server's real reason is in
    # the portal's enrollment log. Never print the token itself.
    {
      echo "easyscep: the server refused the request. Find it in the portal's enrollment log for the reason:"
      echo "  profile:   ${SITE_PROFILE:-unknown}"
      echo "  SCEP URL:  $scep_url"
      echo "  subject:   CN=$cn"
      echo "  key:       RSA $key_size"
      echo "  token id:  $token_id"
    } >&2
  fi
  if restore_previous; then
    echo "easyscep: previous certificate kept ($ES_DIR/device.crt)" >&2
  fi
  if [ -n "$SITE_TOKEN" ]; then
    echo "easyscep: make a new file with: ./easyscep add $cn, and run that" >&2
  else
    echo "easyscep: mint a new token with: $(mint_hint), then run this again" >&2
  fi
  exit 1
}

# getcert_or_die WHAT ARGS...: run getcert; on failure die with its exit code
# and output. (No token ever goes on a getcert command line; it travels as -l FILE.)
getcert_or_die() {
  local what=$1 out rc=0; shift
  out=$(getcert "$@" 2>&1) || rc=$?
  [ "$rc" = 0 ] || die "$what failed (getcert exit $rc): ${out:-no output}"
}

# Our CA entry from `getcert list-cas`, matched case-insensitively (certmonger
# treats nicknames that way when adding/removing). First line: its real name.
find_ca() {
  getcert list-cas 2>/dev/null | awk -v want="$CA_NICK" '
    /^CA \047/ { n = $0; sub(/^CA \047/, "", n); sub(/\047:[ \t]*$/, "", n)
                 cur = (tolower(n) == tolower(want)); if (cur) print n; next }
    cur { print }' || true
}

# Wait until certmonger has fetched the CA/RA certificates (GetCACert runs in
# the background after add-scep-ca); a request sent before that fails with
# CA_UNCONFIGURED.
wait_for_ca() {
  local name=$1 limit=${ES_CA_WAIT:-60} start=$SECONDS info err
  echo "waiting for certmonger to fetch the CA certificates..." >&2
  while :; do
    info=$(getcert list-cas -c "$name" 2>&1 || true)
    ! grep -q 'SCEP CA certificate thumbprint' <<<"$info" || return 0
    err=$(sed -n 's/^[[:space:]]*ca-error: //p' <<<"$info" | head -n1)
    [ -z "$err" ] || die "certmonger could not fetch the CA certificates from $scep_url: $err"
    (( SECONDS - start < limit )) \
      || die "certmonger did not fetch the CA certificates from $scep_url within ${limit}s; check the laptop can reach it (curl -I $scep_url) and run setup again"
    sleep 1
  done
}

# Add our SCEP CA, or reuse it if it has the same URL and TLS CA (-R).
ensure_ca() {
  local add=(-c "$CA_NICK" -u "$scep_url")
  if [ -n "$tls_ca" ]; then
    if [ -n "$tls_ca_src" ]; then
      cat "$tls_ca_src" >"$ES_DIR/scep-tls-ca.pem" && chmod 644 "$ES_DIR/scep-tls-ca.pem" \
        || die "could not write $ES_DIR/scep-tls-ca.pem"
    fi
    add+=(-R "$tls_ca")
  fi
  local entry name="" words
  entry=$(find_ca)
  if [ -n "$entry" ]; then
    name=$(head -n1 <<<"$entry")
    # whole words, so .../scep does not match .../scep2
    words=$(tr -s '[:space:]' '\n' <<<"$entry")
    if [ "$name" != "$CA_NICK" ] || ! grep -qxF -- "$scep_url" <<<"$words" \
       || { [ -n "$tls_ca" ] && [ "$(grep -A1 -xF -- -R <<<"$words" | sed -n 2p)" != "$tls_ca" ]; }; then
      getcert_or_die "removing the old CA entry '$name'" remove-ca -c "$name"
      name=""
    fi
  fi
  if [ -z "$name" ]; then
    getcert_or_die "adding the SCEP CA '$CA_NICK' ($scep_url)" add-scep-ca "${add[@]}"
    name=$CA_NICK
  fi
  wait_for_ca "$CA_NICK"
}

# certmonger saves the -l path in its request file and reads it again on every
# renewal, but the token file is deleted after setup, so renewal would stop at
# NEED_CSR_GEN_PIN. getcert has no option to clear a stored challenge, so stop
# certmonger, drop the challenge_password lines from OUR request file (found by
# its id= line, not its name) and start it again. Renewal is then signed by the
# current certificate, with no challenge.
forget_challenge() {
  local f file="" warn="easyscep: warning: certmonger still refers to the deleted token file, so renewal will fail (NEED_CSR_GEN_PIN)"
  for f in "$CM_REQS"/*; do
    if [ -f "$f" ] && grep -qx "id=$REQ_ID" "$f"; then file=$f; break; fi
  done
  [ -n "$file" ] || { echo "$warn: no request file with id=$REQ_ID in $CM_REQS" >&2; return 0; }
  grep -q challenge_password "$file" || return 0
  systemctl stop certmonger || { echo "$warn: could not stop certmonger to edit $file" >&2; return 0; }
  local tmp; tmp=$(mktemp "$WORK/req.XXXXXX")
  # cat > keeps the file's owner and mode (root, 600)
  if grep -v challenge_password "$file" >"$tmp"; then cat "$tmp" >"$file"
  else echo "$warn: could not edit $file" >&2; fi
  systemctl start certmonger \
    || echo "easyscep: warning: could not start certmonger again; run: sudo systemctl start certmonger" >&2
}

enroll() {
  local tokfile=$WORK/token key=$ES_DIR/device.key crt=$ES_DIR/device.crt ca=$ES_DIR/ca.pem
  # Detect by content: real getcert may exit 0 with no matching entry.
  local info
  info=$(getcert list -i "$REQ_ID" 2>/dev/null || true)
  if grep -qF "Request ID '$REQ_ID'" <<<"$info"; then
    # A previous run: replace our own tracking cleanly.
    getcert_or_die "stopping the previous request $REQ_ID" stop-tracking -i "$REQ_ID"
  fi
  ensure_ca

  backup_previous
  # -m/-M: certmonger keeps these modes on the key and certificate on renewal.
  getcert request -c "$CA_NICK" -I "$REQ_ID" -k "$key" -f "$crt" -F "$ca" \
    -N "CN=$cn" -g "$key_size" -l "$tokfile" -m 0600 -M 0644 -C "$RENEW_HOOK" -w >/dev/null || true

  local info status caerr
  info=$(getcert list -i "$REQ_ID" 2>/dev/null || true)
  status=$(sed -n 's/^[[:space:]]*status: //p' <<<"$info" | head -n1)
  caerr=$(sed -n 's/^[[:space:]]*ca-error: //p' <<<"$info" | head -n1)
  [ "$status" = MONITORING ] || enroll_fail "certmonger status ${status:-unknown}" "$caerr"

  # Post-check: the certificate must match the key and allow client auth.
  local a b
  a=$(openssl x509 -in "$crt" -noout -pubkey 2>/dev/null || true)
  b=$(openssl pkey -in "$key" -pubout 2>/dev/null || true)
  if [ -z "$a" ] || [ "$a" != "$b" ]; then
    rm -f "$key" "$crt"
    enroll_fail "certificate does not match the private key"
  fi
  if ! openssl x509 -in "$crt" -noout -ext extendedKeyUsage 2>/dev/null | grep -q 'TLS Web Client Authentication'; then
    rm -f "$key" "$crt"
    enroll_fail "certificate lacks the TLS Web Client Authentication usage (EKU clientAuth)"
  fi
  discard_previous
  forget_challenge
  chmod 600 "$key"; chmod 644 "$crt"
  if [ -e "$ca" ]; then chmod 644 "$ca"
  else echo "easyscep: warning: certmonger did not write the CA chain $ca; continuing without it" >&2; fi
  echo "enrolled: CN=$cn ($crt)"
}

# Names (one per line) of the kit connections that exist / are active.
nm_names() { nmcli -t -f NAME connection show "$@" 2>/dev/null || true; }

# Delete whichever kit connections exist; tries them all, prints the names it
# could not delete on stdout and returns 1 if any failed.
delete_kit_connections() {
  local existing c rc=0; existing=$(nm_names)
  for c in "${KIT_CONNS[@]}"; do
    if grep -qxF -- "$c" <<<"$existing"; then
      nmcli connection delete "$c" >/dev/null || { echo "$c"; rc=1; }
    fi
  done
  return $rc
}

configure_network() {
  cat "$radius_ca" >"$ES_DIR/radius-ca.pem" && chmod 644 "$ES_DIR/radius-ca.pem" || { net_err="could not write $ES_DIR/radius-ca.pem"; return 1; }
  local failed
  failed=$(delete_kit_connections) || { net_err="could not delete the old kit connection(s) $(echo $failed)"; return 1; }
  local eap=(802-1x.eap tls 802-1x.identity "$cn" 802-1x.client-cert "$ES_DIR/device.crt"
    802-1x.private-key "$ES_DIR/device.key" 802-1x.private-key-password-flags 4
    802-1x.ca-cert "$ES_DIR/radius-ca.pem" 802-1x.domain-suffix-match "$radius_name")
  # priority 100: preferred over NetworkManager's default "Wired connection 1" (0).
  local common=(connection.permissions "" connection.autoconnect yes connection.autoconnect-priority 100)
  made=()
  if [ -n "$ssid" ]; then
    nmcli connection add type wifi con-name easyscep-wifi ssid "$ssid" "${common[@]}" \
      wifi-sec.key-mgmt wpa-eap "${eap[@]}" >/dev/null || { net_err="could not create connection easyscep-wifi"; return 1; }
    made+=(easyscep-wifi)
  fi
  if [ -n "$wired" ]; then
    local ifname=$wired; [ "$wired" != auto ] || ifname='*'
    nmcli connection add type ethernet con-name easyscep-wired ifname "$ifname" "${common[@]}" \
      "${eap[@]}" >/dev/null || { net_err="could not create connection easyscep-wired"; return 1; }
    made+=(easyscep-wired)
  fi
}

# Keep a copy of this script without any token, taken before setup deletes a
# one-time file; install_self installs it. Piped scripts (curl | sudo bash)
# are not real files, so there is nothing to copy.
snapshot_self() {
  local src=${BASH_SOURCE[0]:-}
  if [ -f "$src" ] && [ -r "$src" ]; then
    sed "s/^SITE_TOKEN=.*/SITE_TOKEN=''/" "$src" >"$WORK/self" || rm -f "$WORK/self"
  fi
}

install_self() {
  local dest=$ES_ROOT/usr/local/sbin/easyscep
  local msg="easyscep: could not install /usr/local/sbin/easyscep; copy the setup file there to use status/remove and the automatic reconnect after renewal"
  [ -s "$WORK/self" ] || { echo "$msg" >&2; return 0; }
  mkdir -p "$(dirname "$dest")"
  # temp + mv: never rewrite the file a running copy of this script reads
  cp "$WORK/self" "$dest.new" && chmod 755 "$dest.new" && mv -f "$dest.new" "$dest" \
    || { rm -f "$dest.new"; echo "$msg" >&2; }
}

write_site_conf() {
  local f=$ES_DIR/site.conf
  {
    printf 'SCEP_URL=%q\n' "$scep_url"
    printf 'SSID=%q\n' "$ssid"
    printf 'WIRED=%q\n' "$wired"
    printf 'RADIUS_NAME=%q\n' "$radius_name"
    printf 'CN=%q\n' "$cn"
    printf 'PROFILE=%q\n' "$SITE_PROFILE"
    printf 'TLS_CA=%q\n' "$tls_ca"
    printf 'KIT_VERSION=%q\n' "$KIT_VERSION"
  } >"$f"
  chmod 644 "$f"
}

# One value of device.crt (pass an openssl option, e.g. -serial); empty if unreadable.
cert_field() { openssl x509 -in "$ES_DIR/device.crt" -noout "$1" 2>/dev/null | sed "s/^[a-zA-Z]*=//"; }

cmd_setup() {
  parse_args "$@"
  check_root
  WORK=$(mktemp -d); chmod 700 "$WORK"
  snapshot_self
  validate
  mkdir -p "$ES_DIR"; chmod 755 "$ES_DIR"
  get_token "$WORK/token"
  ensure_certmonger
  enroll
  if ! configure_network; then
    if [ -n "$SITE_TOKEN" ]; then
      die "certificate enrolled, but network configuration failed: $net_err. Fix the problem, then make a new file with: ./easyscep add $cn, and run that."
    fi
    die "certificate enrolled, but network configuration failed: $net_err. Fix the problem and run setup again with a new token ($(mint_hint))."
  fi
  install_self
  write_site_conf
  echo "easyscep: setup complete"
  echo "  CN:          $cn"
  echo "  serial:      $(cert_field -serial)"
  echo "  expires:     $(cert_field -enddate)"
  echo "  connections: ${made[*]}"
}

# Called by certmonger (as root) after each renewal: reconnect with the new cert.
cmd_renewed() {
  local active c; active=$(nm_names --active)
  for c in "${KIT_CONNS[@]}"; do
    if grep -qxF -- "$c" <<<"$active"; then
      nmcli connection up "$c" >/dev/null || echo "easyscep: warning: could not reconnect $c" >&2
    fi
  done
  return 0
}

cmd_status() {
  local info
  if info=$(getcert list -i "$REQ_ID" 2>/dev/null); then
    if grep -qF "Request ID '$REQ_ID'" <<<"$info"; then
      sed -n 's/^[[:space:]]*\(status\|stuck\|ca-error\|expires\): \(.*\)/certmonger \1: \2/p' <<<"$info"
    else
      echo "certmonger status: not tracked"
    fi
  else
    echo "certmonger status: unavailable (run as root for details)"
  fi
  local have=1
  if [ -r "$ES_DIR/device.crt" ] && openssl x509 -in "$ES_DIR/device.crt" -noout 2>/dev/null; then
    openssl x509 -in "$ES_DIR/device.crt" -noout -subject -serial -enddate
    have=0
  else
    echo "no certificate"
  fi
  local existing active c state; existing=$(nm_names); active=$(nm_names --active)
  for c in "${KIT_CONNS[@]}"; do
    grep -qxF -- "$c" <<<"$existing" || continue
    state=inactive; ! grep -qxF -- "$c" <<<"$active" || state=active
    echo "connection $c: $state"
  done
  return $have
}

cmd_remove() {
  check_root
  local serial=""
  [ ! -r "$ES_DIR/device.crt" ] || serial=$(cert_field -serial)
  if command -v getcert >/dev/null 2>&1; then
    getcert stop-tracking -i "$REQ_ID" >/dev/null 2>&1 || true   # not tracked is fine
    getcert remove-ca -c "$CA_NICK" >/dev/null 2>&1 || true
  fi
  local failed
  if ! failed=$(delete_kit_connections); then
    echo "easyscep: warning: could not delete connection(s) $(echo $failed); delete them with: sudo nmcli connection delete <name>" >&2
  fi
  rm -rf "$ES_DIR"
  echo "easyscep: removed (kept $ES_ROOT/usr/local/sbin/easyscep)"
  if [ -n "$serial" ]; then echo "Ask IT to revoke serial $serial"
  else echo "no certificate was found, nothing to revoke"; fi
}

main() {
  local sub=setup
  if [ $# -gt 0 ] && { [[ $1 != -* ]] || [ "$1" = --version ]; }; then sub=$1; shift; fi
  case "$sub" in
    --version|version) echo "easyscep $KIT_VERSION" ;;
    setup) cmd_setup "$@" ;;
    status) cmd_status ;;
    remove) cmd_remove ;;
    renewed) cmd_renewed ;;
    *) usage "unknown command: $sub (setup|status|remove|renewed)" ;;
  esac
}

main "$@"
