#!/usr/bin/env bash
# Step 10 of agentrelay.com/docs/self-hosting/install-gke: create the five Kubernetes Secrets from the local
# secret files, and never change or remove a key that is already in the
# cluster.
#
#   bash create-secrets.sh                # after cloud-sql-setup.sh pre
#
# First install (no Secret exists yet): generates the missing keys
# (selfhost-encryption-key, SUMMARY_MASTER_KEYS and the six tokens) into the
# local folder, then creates the five Secrets.
# Rerun on an existing install: generates nothing. Every key in the local
# folder must already match the cluster, or be missing there; a key missing
# from the cluster is added on its own. Keys that exist only in the cluster
# (for example oidc-client-secret) are left alone. It stops, changing nothing,
# when the local folder lacks a generated key, or when a local value differs
# from the cluster's. It never prints a value.
# Rotating a key is not done here.
#
# Needs kubectl (on the cluster), python3 and openssl.
set -euo pipefail
NS="${NAMESPACE:-agent-relay}"
S="${SECRET_FILES:-${STATE_DIR:-$HOME/.agent-relay-install}/secret-files}"
NAMES="agent-relay-secrets agent-relay-read-api agent-relay-ingest-edge-runtime search-indexer-runtime search-indexer-owner"
# The keys this step generates, all in agent-relay-secrets.
GENERATED="selfhost-bootstrap-token selfhost-setup-key relaycast-internal-secret relaycast-workspace-bootstrap-secret relaycontrol-introspect-secret session-read-api-secret selfhost-encryption-key SUMMARY_MASTER_KEYS"
for tool in kubectl python3 openssl; do
  command -v "$tool" >/dev/null || { echo "missing tool: $tool" >&2; exit 1; }
done
for n in $NAMES; do
  [ -d "$S/$n" ] || { echo "no $S/$n: run cloud-sql-setup.sh pre first" >&2; exit 1; }
done
# Every Secret folder must be a real directory (not a link), and every entry in
# it a regular file (hidden entries are ignored): anything else stops the run.
bad=""
for n in $NAMES; do
  if [ -L "$S/$n" ]; then bad="$bad $n/"; continue; fi
  for f in "$S/$n"/*; do
    [ -e "$f" ] || [ -L "$f" ] || continue
    if [ ! -f "$f" ] || [ -L "$f" ]; then bad="$bad $n/${f##*/}"; fi
  done
done
if [ -n "$bad" ]; then
  echo "not a regular file:$bad. Nothing changed. Restore the folder from your secret store, then run this again." >&2
  exit 3
fi
umask 077
# One run at a time per folder: two overlapping first installs must not both
# generate keys. The lock lives in the folder's root, which is never uploaded.
LOCK="$S/.secret-files.lock"
mkdir "$LOCK" 2>/dev/null || {
  echo "another run (create-secrets.sh or helm-secrets-prepare.sh) holds $LOCK; wait for it, or remove the directory if no run is active" >&2
  exit 5
}
WORK=""
trap 'if [ -n "$WORK" ]; then rm -rf "$WORK"; fi; rmdir "$LOCK" 2>/dev/null' EXIT
WORK="$(mktemp -d)"
install_file() { # install_file SRC DEST REPLACE(0|1): never leaves a partial key or a temp file
  local src="$1" dest="$2" replace="$3" tmp
  if [ -d "$dest" ] || [ -L "$dest" ]; then
    echo "$dest is not a regular file; nothing written" >&2; return 4
  fi
  # mktemp creates a new file and refuses an existing path, so a stale or
  # planted link with a temporary-looking name can't redirect the key.
  tmp="$(mktemp "$(dirname "$dest")/.${dest##*/}.tmp.XXXXXX")" || { echo "could not write $dest; nothing written" >&2; return 1; }
  if [ ! -f "$tmp" ] || [ -L "$tmp" ] || [ -s "$tmp" ]; then  # must be the new, empty, regular file
    # Remove it unless it is a real directory (removing a link leaves its target).
    if [ -L "$tmp" ] || [ ! -d "$tmp" ]; then rm -f "$tmp"; fi
    echo "could not create a temporary file for $dest; nothing written" >&2; return 1
  fi
  cp "$src" "$tmp" || { rm -f "$tmp"; echo "could not write $dest; nothing written" >&2; return 1; }
  if [ "$replace" = 1 ] && [ -f "$dest" ]; then
    mv -f "$tmp" "$dest" || { rm -f "$tmp"; echo "could not write $dest; nothing written" >&2; return 1; }
  elif ln "$tmp" "$dest" 2>/dev/null; then  # fails if $dest exists: never overwrite a key
    rm -f "$tmp"
  else
    rm -f "$tmp"; echo "$dest changed while this ran; run this again" >&2; return 4
  fi
  # The destination must now be a regular file holding exactly this content.
  if [ ! -f "$dest" ] || [ -L "$dest" ] || ! cmp -s "$src" "$dest"; then
    echo "$dest changed while this ran; run this again" >&2; return 4
  fi
}
rand_hex() { # 64 hex characters, or stop: never save a short or empty key
  local v; v="$(openssl rand -hex 32)" || return 1
  [ "${#v}" = 64 ] || { echo "openssl rand returned no key" >&2; return 1; }
  printf '%s' "$v"
}

echo "kubectl context: $(kubectl config current-context 2>/dev/null || echo '(none)'), namespace: $NS"

# Read the cluster once: for each Secret that exists, its resourceVersion and
# its keys (values stay in $WORK, mode 0600, and are never printed).
for n in $NAMES; do
  if kubectl -n "$NS" get secret "$n" -o json >"$WORK/$n.json" 2>"$WORK/$n.err"; then :
  elif grep -q NotFound "$WORK/$n.err"; then rm -f "$WORK/$n.json"
  else echo "could not read Secret $n; nothing changed" >&2; exit 1
  fi
done
existing=""
for n in $NAMES; do [ -f "$WORK/$n.json" ] && existing="$existing $n"; done
cluster_has() { # cluster_has SECRET KEY
  [ -f "$WORK/$1.json" ] && python3 -c 'import json,sys; sys.exit(0 if sys.argv[2] in (json.load(open(sys.argv[1])).get("data") or {}) else 1)' "$WORK/$1.json" "$2"
}

# Work on a copy of the local folder: generated keys and the introspect copy go
# there first, and reach $S only after every check below has passed, so a
# refused run leaves the folder exactly as it was.
STAGE="$WORK/stage"
mkdir -p "$STAGE"
cp -R "$S/." "$STAGE/"

# Generate keys only on a first install: when none of the five Secrets exists.
# On an existing install a missing generated key stops the run, even when the
# cluster lacks it too, because a new encryption key would make data
# encrypted with the old one unreadable.
missing=""
for k in $GENERATED; do
  [ -s "$STAGE/agent-relay-secrets/$k" ] && continue
  if [ -n "$existing" ]; then missing="$missing $k"; continue; fi
  v="$(rand_hex)" || { echo "could not generate $k; nothing changed" >&2; exit 1; }
  if [ "$k" = SUMMARY_MASTER_KEYS ]; then v="k1:$v"; fi
  printf '%s' "$v" >"$STAGE/agent-relay-secrets/$k"
done
if [ -n "$missing" ]; then
  echo "This install already has Secrets in the cluster (${existing# }), but the local folder lacks these generated keys:$missing" >&2
  echo "Nothing changed. Restore $S from your secret store (step 8), then run this again." >&2
  exit 3
fi
if [ ! -s "$STAGE/agent-relay-ingest-edge-runtime/introspect-secret" ] \
   || ! cmp -s "$STAGE/agent-relay-secrets/relaycontrol-introspect-secret" "$STAGE/agent-relay-ingest-edge-runtime/introspect-secret"; then
  if cluster_has agent-relay-ingest-edge-runtime introspect-secret && [ -s "$STAGE/agent-relay-ingest-edge-runtime/introspect-secret" ]; then
    echo "agent-relay-ingest-edge-runtime introspect-secret differs from relaycontrol-introspect-secret locally; nothing changed" >&2
    exit 3
  fi
  cp "$STAGE/agent-relay-secrets/relaycontrol-introspect-secret" "$STAGE/agent-relay-ingest-edge-runtime/introspect-secret"
fi

# Plan every Secret before changing any: refuse on the first difference.
# plan.py writes $WORK/<name>.patch (a JSON patch that first tests the
# resourceVersion read above, then adds only the missing keys) and prints one
# line per Secret: "<name> create", "<name> add <n>" or "<name> unchanged".
cat >"$WORK/plan.py" <<'PY'
import base64, json, os, sys
work, src, name = sys.argv[1:4]
local = {}
d = os.path.join(src, name)
for k in sorted(os.listdir(d)):
    p = os.path.join(d, k)
    if os.path.isfile(p) and not k.startswith("."):
        local[k] = base64.b64encode(open(p, "rb").read()).decode()
live_path = os.path.join(work, name + ".json")
if not os.path.exists(live_path):
    print(name, "create"); sys.exit(0)
live = json.load(open(live_path))
data = live.get("data") or {}
differ = [k for k in local if k in data and data[k] != local[k]]
if differ:
    print("%s: these local keys differ from the cluster: %s" % (name, " ".join(differ)), file=sys.stderr)
    sys.exit(3)
add = [k for k in local if k not in data]
if not add:
    print(name, "unchanged"); sys.exit(0)
ops = [{"op": "test", "path": "/metadata/resourceVersion", "value": live["metadata"]["resourceVersion"]}]
if "data" not in live:
    ops.append({"op": "add", "path": "/data", "value": {}})
ops += [{"op": "add", "path": "/data/" + k.replace("~", "~0").replace("/", "~1"), "value": local[k]} for k in add]
with open(os.path.join(work, name + ".patch"), "w") as f:
    json.dump(ops, f)
print(name, "add", len(add))
PY
: >"$WORK/plan"
for n in $NAMES; do
  python3 "$WORK/plan.py" "$WORK" "$STAGE" "$n" >>"$WORK/plan" \
    || { echo "Nothing changed. Make the local folder match the cluster (restore it from your secret store), then run this again." >&2; exit 3; }
done

# Every check passed: save what this run made in the copy (generated keys, the
# introspect copy) to $S before the cluster gets it, so the folder never lacks
# a key the cluster has.
# A generated key is written only if the file still doesn't exist (noclobber),
# or exists but is empty (an interrupted earlier write: it holds no key, and
# the lock means no other run is writing it). Only the derived introspect copy
# may replace a file that has content.
for n in $NAMES; do
  for f in "$STAGE/$n"/*; do
    [ -f "$f" ] || continue
    dest="$S/$n/${f##*/}"
    cmp -s "$f" "$dest" 2>/dev/null && continue
    replace=0
    if [ -f "$dest" ] && { [ ! -s "$dest" ] || [ "$dest" = "$S/agent-relay-ingest-edge-runtime/introspect-secret" ]; }; then replace=1; fi
    rc=0; install_file "$f" "$dest" "$replace" || rc=$?
    [ "$rc" = 0 ] || { echo "Nothing was written to the cluster." >&2; exit "$rc"; }
  done
done

while read -r n action count; do
  case "$action" in
    create)
      # create fails if someone created the Secret since it was read: run again.
      files=()
      for f in "$STAGE/$n"/*; do [ -f "$f" ] && files+=(--from-file="$f"); done
      if ! kubectl -n "$NS" create secret generic "$n" ${files[@]+"${files[@]}"} >/dev/null 2>"$WORK/kubectl.err"; then
        if grep -q 'already exists' "$WORK/kubectl.err"; then
          echo "secret/$n: create refused (it appeared while this ran); run this again" >&2; exit 4
        fi
        echo "secret/$n: kubectl create failed:" >&2; head -3 "$WORK/kubectl.err" >&2; exit 1
      fi
      echo "secret/$n created" ;;
    add)
      # The resourceVersion test makes this fail, changing nothing, if the
      # Secret changed since it was read: run again.
      if ! kubectl -n "$NS" patch secret "$n" --type json --patch-file "$WORK/$n.patch" >/dev/null 2>"$WORK/kubectl.err"; then
        read_rv="$(python3 -c 'import json,sys; print(json.load(open(sys.argv[1]))["metadata"]["resourceVersion"])' "$WORK/$n.json")"
        now_rv="$(kubectl -n "$NS" get secret "$n" -o json 2>/dev/null \
          | python3 -c 'import json,sys; print(json.load(sys.stdin)["metadata"]["resourceVersion"])' 2>/dev/null || true)"
        if [ -n "$now_rv" ] && [ "$now_rv" != "$read_rv" ]; then
          echo "secret/$n: patch refused (the Secret changed while this ran), nothing written to it; run this again" >&2; exit 4
        fi
        echo "secret/$n: kubectl patch failed, nothing written to it:" >&2; head -3 "$WORK/kubectl.err" >&2; exit 1
      fi
      echo "secret/$n added $count missing key(s); existing keys unchanged" ;;
    unchanged) echo "secret/$n unchanged" ;;
  esac
done <"$WORK/plan"
