#!/usr/bin/env bash
# Fabryka AI Tailscale bootstrap. Public source: https://setup.fabryka.ai/install.sh
# It deliberately does not edit OpenSSH or tailnet policy, or open public port 22.
set -Eeuo pipefail

# Public recovery key for the operator's Mac. This is not a private key or a credential.
readonly BOOTSTRAP_PUBLIC_KEY='ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIBdDn1OfvTkbduhhxEf8byYVOXn35kUkfhAIwvKar7YZ kacper@mac-1.home'

if [[ ${EUID:-$(id -u)} -ne 0 ]]; then
  echo 'Run as root, for example: curl ... | sudo bash' >&2
  exit 1
fi
if [[ $(uname -s) != Linux ]]; then
  echo 'This bootstrap currently supports Linux only.' >&2
  exit 1
fi
if ! command -v curl >/dev/null 2>&1; then
  echo 'curl is required to download the official Tailscale installer.' >&2
  exit 1
fi

echo '==> Adding the operator SSH public key for root recovery access'
install -d -m 0700 /root/.ssh
touch /root/.ssh/authorized_keys
chmod 0600 /root/.ssh/authorized_keys
if ! grep -qxF "$BOOTSTRAP_PUBLIC_KEY" /root/.ssh/authorized_keys; then
  printf '%s\n' "$BOOTSTRAP_PUBLIC_KEY" >> /root/.ssh/authorized_keys
fi

echo '==> Installing or updating Tailscale from tailscale.com'
curl --proto '=https' --tlsv1.2 -fsSL https://tailscale.com/install.sh | sh

if command -v systemctl >/dev/null 2>&1; then
  systemctl enable --now tailscaled
fi

running=0
if tailscale status --json 2>/dev/null | grep -Eq '"BackendState"[[:space:]]*:[[:space:]]*"Running"'; then
  running=1
fi

if (( running )); then
  echo '==> Existing tailnet connection detected; enabling Tailscale SSH'
  tailscale set --ssh
else
  echo '==> Joining tailnet and enabling Tailscale SSH'
  args=(up --ssh)
  if [[ -n ${TS_AUTHKEY:-} ]]; then
    args+=(--auth-key="$TS_AUTHKEY")
  else
    echo 'Open the sign-in URL printed below in your browser to authorize this server.'
  fi
  if [[ -n ${TS_HOSTNAME:-} ]]; then
    args+=(--hostname="$TS_HOSTNAME")
  fi
  tailscale "${args[@]}"
fi

echo
echo '==> Tailscale SSH is enabled on this server.'
echo "Machine name: $(hostname)"
echo "Tailscale IPv4: $(tailscale ip -4 2>/dev/null || true)"
echo 'From a device in this tailnet: tailscale ssh root@<machine-name>'
echo 'If SSH is denied, review the SSH policy in the Tailscale admin console.'
