#!/usr/bin/env bash
# Bootstrap a fresh Ubuntu devbox using a six-digit enrolment code.
# Usage: curl -fsSL https://devbox.pyragroup.ai | sudo bash
set -euo pipefail
umask 077

ENROL_SERVICE="${ENROL_SERVICE:-https://devbox.pyragroup.ai}"
ENROL_SERVICE="${ENROL_SERVICE%/}"
ENROL_REPO="${ENROL_REPO:-https://onedev.pyragroup.ai/it-ops/devbox.git}"
ENROL_WORK_BASE="${ENROL_WORK_BASE:-/var/tmp}"
ENROL_TTY="${ENROL_TTY:-/dev/tty}"

die() {
  printf 'devbox: %s\n' "$*" >&2
  exit 1
}

if [[ -z "${ROOT:-}" && "$(id -u)" -ne 0 ]]; then
  die "run this as root"
fi

command -v curl >/dev/null 2>&1 || die "curl is required"
command -v python3 >/dev/null 2>&1 || die "python3 is required"
[[ -r "$ENROL_TTY" ]] || die "cannot read enrolment code from $ENROL_TTY"

if [[ -c "$ENROL_TTY" && -w "$ENROL_TTY" ]]; then
  printf 'Enrolment code: ' >"$ENROL_TTY"
  IFS= read -r -s code <"$ENROL_TTY" || die "failed to read enrolment code"
  printf '\n' >"$ENROL_TTY"
else
  IFS= read -r code <"$ENROL_TTY" || die "failed to read enrolment code"
fi

code="${code//$'\r'/}"
code="${code//[[:space:]]/}"
[[ "$code" =~ ^[0-9]{6}$ ]] || die "enrolment code must be six digits"

workdir="$(mktemp -d "${ENROL_WORK_BASE%/}/devbox-enrol.XXXXXX")"
chmod 700 "$workdir"
cleanup() {
  rm -rf "$workdir"
}
trap cleanup EXIT

raw_file="$workdir/response.json"
enrolment_file="$workdir/enrolment.json"
clone_dir="$workdir/devbox"

http_status="$(
  printf '%s' "$code" \
    | python3 -c 'import json, sys; sys.stdout.write(json.dumps({"code": sys.stdin.read()}))' \
    | curl -sS --max-time 30 \
        -H 'Content-Type: application/json' \
        -o "$raw_file" \
        -w '%{http_code}' \
        --data-binary @- \
        "${ENROL_SERVICE%/}/enrolments"
)" || die "could not reach enrolment service"
unset code

if [[ "$http_status" != "200" ]]; then
  die "enrolment service refused the code (HTTP $http_status)"
fi

if ! command -v git >/dev/null 2>&1; then
  DEBIAN_FRONTEND=noninteractive apt-get update -qq
  DEBIAN_FRONTEND=noninteractive apt-get install -y -qq git
fi

basic_auth="$(
  python3 - "$raw_file" "$enrolment_file" "$ENROL_SERVICE" <<'PY'
import base64
import json
import os
import sys

raw_path, out_path, service_url = sys.argv[1], sys.argv[2], sys.argv[3]
required = ("id", "session", "onedev_user", "onedev_token", "slack_webhook")

with open(raw_path, encoding="utf-8") as fh:
    doc = json.load(fh)

if not isinstance(doc, dict) or any(not isinstance(doc.get(k), str) or not doc[k] for k in required):
    sys.exit("invalid enrolment response")

doc["service"] = service_url
fd = os.open(out_path, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
with os.fdopen(fd, "w", encoding="utf-8") as out:
    json.dump(doc, out, indent=2)
    out.write("\n")

creds = f"{doc['onedev_user']}:{doc['onedev_token']}".encode("utf-8")
sys.stdout.write(base64.b64encode(creds).decode("ascii"))
PY
)" || die "enrolment service returned an invalid response"
rm -f "$raw_file"

if [[ "$ENROL_REPO" == http://* || "$ENROL_REPO" == https://* ]]; then
  GIT_TERMINAL_PROMPT=0 \
    GIT_CONFIG_COUNT=1 \
    GIT_CONFIG_KEY_0=http.extraHeader \
    GIT_CONFIG_VALUE_0="Authorization: Basic $basic_auth" \
    git clone --quiet --depth 1 --branch main --single-branch "$ENROL_REPO" "$clone_dir"
else
  GIT_TERMINAL_PROMPT=0 \
    git clone --quiet --depth 1 --branch main --single-branch "$ENROL_REPO" "$clone_dir"
fi
unset basic_auth

exec_script="$clone_dir/scripts/enrol.sh"
[[ -f "$exec_script" ]] || die "cloned repository does not contain scripts/enrol.sh"
bash "$exec_script" --enrolment "$enrolment_file"
