#!/usr/bin/env bash
# Howard's ZeroTier + SSH onboarder — Mac + Linux.
#
# Two modes:
#   curl -fsSL https://zerotier.howardkessa.top/join.sh | bash             # permanent (default)
#   curl -fsSL https://zerotier.howardkessa.top/join.sh | bash -s -- temp  # temporary
#
# Temporary mode is identical to permanent except it prints the leave/uninstall
# instructions prominently at the end so the user knows how to remove themselves.

set -euo pipefail

MODE="${1:-perm}"
case "$MODE" in
  perm|permanent) MODE_LABEL="Permanent" ;;
  temp|temporary) MODE_LABEL="Temporary (one-off session)" ;;
  *) echo "Unknown mode: $MODE (expected: perm or temp)"; exit 2 ;;
esac

NETWORK_ID="f3797ba7a858725b"
HOWARDS_NAME="Howard Kessa"
LEAVE_URL="https://zerotier.howardkessa.top/leave.sh"

# Howard's SSH public key (templated at build time, baked into the served script).
HOWARDS_PUBKEY='ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIHE4vY5NhcDdXbSUqqNii77uAxMjA4GjFtW0w70Rkdfa marky.kessa.ky@gmail.com'

c_g=$'\033[32m'; c_y=$'\033[33m'; c_r=$'\033[31m'; c_b=$'\033[1m'; c_x=$'\033[0m'

banner() {
  echo "${c_b}════════════════════════════════════════════════════════════${c_x}"
  echo "${c_b}  ${HOWARDS_NAME}'s ZeroTier + SSH onboarder${c_x}"
  echo "${c_b}  Mode:    ${MODE_LABEL}${c_x}"
  echo "${c_b}  Network: ${NETWORK_ID}${c_x}"
  echo "${c_b}════════════════════════════════════════════════════════════${c_x}"
  echo
  echo "This script will:"
  echo "  1) Install ZeroTier (if needed) and join ${HOWARDS_NAME}'s network"
  echo "  2) Enable Remote Login (SSH server) on this machine"
  echo "  3) Add ${HOWARDS_NAME}'s public SSH key to your authorized_keys"
  echo "  4) Print your ZeroTier node ID so ${HOWARDS_NAME} can authorize you"
  echo
}

need_sudo() {
  if [ "$(id -u)" -ne 0 ] && ! sudo -n true 2>/dev/null; then
    echo "${c_y}This script needs sudo (to install + control ZeroTier and SSH).${c_x}"
    sudo -v || { echo "${c_r}sudo declined. Cannot continue.${c_x}"; exit 1; }
  fi
}

install_zt_macos() {
  if command -v zerotier-cli >/dev/null 2>&1; then
    echo "${c_g}✓ ZeroTier already installed${c_x}"
    return
  fi
  echo "Installing ZeroTier..."
  if command -v brew >/dev/null 2>&1; then
    brew install --cask zerotier-one
  else
    echo "${c_y}Homebrew not found. Falling back to direct .pkg install.${c_x}"
    PKG_URL="https://download.zerotier.com/dist/ZeroTier%20One.pkg"
    TMP_PKG="$(mktemp -d)/zerotier.pkg"
    curl -fsSL "$PKG_URL" -o "$TMP_PKG"
    sudo installer -pkg "$TMP_PKG" -target /
    rm -f "$TMP_PKG"
  fi
  for i in 1 2 3 4 5 6 7 8 9 10; do
    command -v zerotier-cli >/dev/null 2>&1 && break
    sleep 1
  done
}

install_zt_linux() {
  if command -v zerotier-cli >/dev/null 2>&1; then
    echo "${c_g}✓ ZeroTier already installed${c_x}"
    return
  fi
  echo "Installing ZeroTier (official installer)..."
  curl -fsSL https://install.zerotier.com | sudo bash
}

enable_ssh_macos() {
  echo
  echo "Enabling Remote Login (SSH server) on this Mac..."
  if sudo systemsetup -getremotelogin 2>/dev/null | grep -qi "On"; then
    echo "${c_g}✓ Remote Login already on${c_x}"
  else
    sudo systemsetup -setremotelogin on >/dev/null 2>&1 || true
    if sudo systemsetup -getremotelogin 2>/dev/null | grep -qi "On"; then
      echo "${c_g}✓ Remote Login enabled${c_x}"
    else
      echo "${c_y}⚠ Could not enable Remote Login automatically (newer macOS may require manual toggle).${c_x}"
      echo "${c_y}  Go to System Settings → General → Sharing → toggle Remote Login on.${c_x}"
    fi
  fi
}

enable_ssh_linux() {
  echo
  echo "Enabling SSH server on this Linux box..."
  if ! command -v sshd >/dev/null 2>&1 && ! systemctl list-unit-files 2>/dev/null | grep -qE "^(ssh|sshd)\."; then
    if command -v apt-get >/dev/null 2>&1; then
      sudo apt-get update -qq
      sudo apt-get install -yq openssh-server
    elif command -v dnf >/dev/null 2>&1; then
      sudo dnf install -y openssh-server
    elif command -v yum >/dev/null 2>&1; then
      sudo yum install -y openssh-server
    elif command -v pacman >/dev/null 2>&1; then
      sudo pacman -S --noconfirm openssh
    else
      echo "${c_y}⚠ Could not auto-install openssh-server (unknown package manager). Install it manually.${c_x}"
      return
    fi
  fi
  SVC=ssh
  systemctl list-unit-files 2>/dev/null | grep -q "^sshd\." && SVC=sshd
  sudo systemctl enable --now "$SVC" 2>/dev/null || sudo service "$SVC" start 2>/dev/null || true
  echo "${c_g}✓ SSH server running${c_x}"
}

install_howards_key() {
  echo
  echo "Adding ${HOWARDS_NAME}'s public key to your authorized_keys..."
  TARGET_USER="${SUDO_USER:-$USER}"
  TARGET_HOME=$(eval echo "~$TARGET_USER")
  SSH_DIR="$TARGET_HOME/.ssh"
  AUTH="$SSH_DIR/authorized_keys"
  sudo -u "$TARGET_USER" mkdir -p "$SSH_DIR"
  sudo -u "$TARGET_USER" touch "$AUTH"
  sudo chmod 700 "$SSH_DIR"
  sudo chmod 600 "$AUTH"
  if sudo grep -qF "$HOWARDS_PUBKEY" "$AUTH" 2>/dev/null; then
    echo "${c_g}✓ Key already present (no changes made)${c_x}"
  else
    echo "$HOWARDS_PUBKEY" | sudo tee -a "$AUTH" >/dev/null
    echo "${c_g}✓ Key installed for user '$TARGET_USER'${c_x}"
  fi
}

join_network() {
  echo
  echo "Joining ZeroTier network ${NETWORK_ID}..."
  sudo zerotier-cli join "$NETWORK_ID" >/dev/null
  NODE_ID=$(sudo zerotier-cli info | awk '{print $3}')
  echo
  echo "${c_g}✓ Joined.${c_x}"
  echo "${c_b}Your ZeroTier node ID:${c_x}  ${c_g}${NODE_ID}${c_x}"
  echo
  echo "${c_y}Send this node ID to ${HOWARDS_NAME} so it can be authorized.${c_x}"
}

wait_for_authorization() {
  echo
  echo "Waiting for authorization (checking every 10s, up to 5 min)..."
  for i in $(seq 1 30); do
    STATUS=$(sudo zerotier-cli listnetworks 2>/dev/null | awk -v n="$NETWORK_ID" '$3==n {print $6,$9}' | head -1)
    OK=$(echo "$STATUS" | awk '{print $1}')
    IP=$(echo "$STATUS" | awk '{print $2}')
    if [ "$OK" = "OK" ] && [ -n "$IP" ] && [ "$IP" != "-" ]; then
      echo
      echo "${c_g}✓ Authorized.${c_x}"
      echo "${c_g}  ZeroTier IP: ${IP}${c_x}"
      echo "${c_g}  SSH user:    ${SUDO_USER:-$USER}${c_x}"
      echo
      echo "${HOWARDS_NAME} can now SSH to this machine:  ssh ${SUDO_USER:-$USER}@${IP}"
      return 0
    fi
    printf "."
    sleep 10
  done
  echo
  echo "${c_y}Still not authorized after 5 minutes. Authorization may take longer.${c_x}"
  echo "${c_y}Once ${HOWARDS_NAME} approves you, no further action is needed.${c_x}"
  echo "${c_y}Check status anytime with: sudo zerotier-cli listnetworks${c_x}"
}

main() {
  banner
  need_sudo
  OS="$(uname -s)"
  case "$OS" in
    Darwin) install_zt_macos; enable_ssh_macos ;;
    Linux)  install_zt_linux; enable_ssh_linux ;;
    *)
      echo "${c_r}Unsupported OS for this script: ${OS}${c_x}"
      echo "If you're on Windows, use the PowerShell script (join.ps1) instead."
      exit 1
      ;;
  esac
  install_howards_key
  join_network
  wait_for_authorization
  if [ "$MODE" = "temp" ] || [ "$MODE" = "temporary" ]; then
    echo
    echo "${c_b}════════════════════════════════════════════════════════════${c_x}"
    echo "${c_b}  When you're done, remove yourself with one command:${c_x}"
    echo "${c_b}════════════════════════════════════════════════════════════${c_x}"
    echo
    echo "    ${c_g}curl -fsSL ${LEAVE_URL} | bash${c_x}"
    echo
    echo "  That removes ${HOWARDS_NAME}'s SSH key from your machine and"
    echo "  leaves the ZeroTier network. You can save this URL for later:"
    echo "    ${LEAVE_URL}"
    echo
  fi
}

main "$@"
