#!/bin/sh
set -eu

if [ "$(id -u)" -ne 0 ]; then
  echo 'Run with administrator privileges: sudo citadel-activate' >&2
  exit 1
fi

for command in citadel-client wg sha256sum awk sed date install mktemp; do
  command -v "$command" >/dev/null 2>&1 || { echo "Required command is missing: $command" >&2; exit 1; }
done

configuration='/etc/citadel/client.conf'
license='/etc/citadel/license.key'
state='/var/lib/citadel'
[ -f "$configuration" ] || { echo 'Missing /etc/citadel/client.conf.' >&2; exit 1; }
[ -f "$license" ] || { echo 'Configure the license first: sudo citadel-configure-license' >&2; exit 1; }

endpoint=$(sed -n 's/^[[:space:]]*activation_endpoint[[:space:]]*=[[:space:]]*//p' "$configuration" | sed -n '1p')
[ -n "$endpoint" ] || { echo 'activation_endpoint is not configured.' >&2; exit 1; }

install -d -o root -g root -m 0700 "$state" "$state/routes"
private="$state/wireguard-private.key"
public="$state/wireguard-public.key"
fingerprint="$state/device-fingerprint.txt"

if [ ! -f "$private" ] || [ ! -f "$public" ]; then
  umask 077
  private_tmp=$(mktemp "$state/.private.XXXXXX")
  public_tmp=$(mktemp "$state/.public.XXXXXX")
  trap 'rm -f "$private_tmp" "$public_tmp"' EXIT HUP INT TERM
  wg genkey > "$private_tmp"
  wg pubkey < "$private_tmp" > "$public_tmp"
  chmod 0600 "$private_tmp" "$public_tmp"
  mv -f "$private_tmp" "$private"
  mv -f "$public_tmp" "$public"
  trap - EXIT HUP INT TERM
fi

machine_id=''
for candidate in /etc/machine-id /var/lib/dbus/machine-id; do
  if [ -r "$candidate" ]; then machine_id=$(sed -n '1p' "$candidate"); break; fi
done
[ -n "$machine_id" ] || { echo 'A stable Linux machine identifier is unavailable.' >&2; exit 1; }
printf 'citadel-linux:%s' "$machine_id" | sha256sum | awk '{ print $1 }' > "$fingerprint"
chmod 0600 "$private" "$public" "$fingerprint"

route="$state/routes/route-$(date -u +%Y%m%d-%H%M%S).json"
citadel-client -activate \
  -activation-endpoint "$endpoint" \
  -license-file "$license" \
  -device-fingerprint-file "$fingerprint" \
  -wireguard-public-key-file "$public" \
  -route-output "$route"
chmod 0600 "$route"

echo "Acknowledged route staged at $route"
echo 'The route has not been installed or activated. Review it before configuring WireGuard.'
