#!/usr/bin/env bash
# Prepares a Linux server to host Tazmu computers. Published as
# https://tazmu.xyz/computer.sh; Settings → Computer shows the command:
#
#   curl -fsSL https://tazmu.xyz/computer.sh | sudo bash -s -- --key "ssh-ed25519 AAAA... tazmu"
#
# What it does, and nothing else:
#   1. installs Docker if it is missing and starts it
#   2. creates a `tazmu` user that can sign in only with the key Tazmu
#      generated, and lets it use Docker
#   3. pulls the computer image so the first desktop starts quickly
#
# Running it again is safe: every step checks before it changes anything.
# Docker access is root-equivalent on this server. Use a server you can
# dedicate to Tazmu computers.
set -euo pipefail

# Everything runs from main, so a piped script is read in full before any
# step can consume the rest of stdin.
main() {
KEY=""
TAZMU_USER="tazmu"
IMAGE="registry.tazmu.xyz/tazmu/computer:latest"
PULL=1

usage() {
  cat <<'EOF'
Usage: computer.sh --key "ssh-ed25519 AAAA... tazmu" [--user tazmu] [--image IMAGE] [--no-pull]

  --key      Public key shown in Tazmu, Settings > Computer (required)
  --user     Account Tazmu signs in as (default: tazmu)
  --image    Computer image to pull (default: registry.tazmu.xyz/tazmu/computer:latest)
  --no-pull  Skip the image pull; Tazmu pulls it on first use
EOF
}

say() { printf '\033[1m==>\033[0m %s\n' "$*"; }
ok() { printf '    \033[32mok\033[0m %s\n' "$*"; }
warn() { printf '    \033[33mnote\033[0m %s\n' "$*" >&2; }
die() { printf '\033[31merror:\033[0m %s\n' "$*" >&2; exit 1; }

while [ $# -gt 0 ]; do
  case "$1" in
    --key) KEY="${2:-}"; shift 2 ;;
    --key=*) KEY="${1#--key=}"; shift ;;
    --user) TAZMU_USER="${2:-}"; shift 2 ;;
    --user=*) TAZMU_USER="${1#--user=}"; shift ;;
    --image) IMAGE="${2:-}"; shift 2 ;;
    --image=*) IMAGE="${1#--image=}"; shift ;;
    --no-pull) PULL=0; shift ;;
    -h|--help) usage; exit 0 ;;
    *) usage >&2; die "unknown option: $1" ;;
  esac
done

[ -n "$KEY" ] || { usage >&2; die "--key is required. Copy the full command from Tazmu."; }
# One plain ed25519 public key, nothing an authorized_keys line could
# interpret as options.
printf '%s' "$KEY" | grep -Eq '^ssh-ed25519 [A-Za-z0-9+/]+={0,3}( [A-Za-z0-9_.@-]+)?$' \
  || die "--key must be the ssh-ed25519 public key Tazmu shows"
printf '%s' "$TAZMU_USER" | grep -Eq '^[a-z_][a-z0-9_-]{0,31}$' || die "--user must be a plain Linux user name"
printf '%s' "$IMAGE" | grep -Eq '^[A-Za-z0-9][A-Za-z0-9._/:@-]*$' || die "--image is not an image reference"

[ "$(uname -s)" = Linux ] || die "this script runs on a Linux server"
[ "$(id -u)" -eq 0 ] || die "run it with sudo (the command from Tazmu already does)"
case "$(uname -m)" in
  x86_64|amd64|aarch64|arm64) ;;
  *) die "unsupported CPU architecture $(uname -m); Tazmu computers need x86_64 or arm64" ;;
esac

have() { command -v "$1" >/dev/null 2>&1; }

start_service() {
  if have systemctl && [ -d /run/systemd/system ]; then
    systemctl enable --now "$1" >/dev/null 2>&1 || systemctl start "$1"
  elif have rc-service; then
    rc-update add "$1" default >/dev/null 2>&1 || true
    rc-service "$1" start >/dev/null 2>&1 || true
  elif have service; then
    service "$1" start >/dev/null 2>&1 || true
  fi
}

# ── 1. Docker ────────────────────────────────────────────────────────────
say "Docker"
if have docker; then
  ok "already installed ($(docker --version 2>/dev/null | head -n1))"
else
  have curl || die "curl is required to install Docker"
  if have apk; then
    apk add --no-cache docker >/dev/null
  else
    # Docker's own installer covers Ubuntu, Debian, Fedora, CentOS, RHEL
    # and Raspberry Pi OS.
    curl -fsSL https://get.docker.com | sh
  fi
  ok "installed"
fi
start_service docker
for _ in $(seq 1 30); do
  docker info >/dev/null 2>&1 && break
  sleep 1
done
docker info >/dev/null 2>&1 || die "Docker is installed but not running. Start it, then run this command again."
ok "running"

# ── 2. The tazmu user ────────────────────────────────────────────────────
say "User $TAZMU_USER"
if id "$TAZMU_USER" >/dev/null 2>&1; then
  ok "exists"
else
  if have useradd; then
    useradd --create-home --shell /bin/sh "$TAZMU_USER"
  else
    adduser -D -s /bin/sh "$TAZMU_USER"
  fi
  ok "created"
fi
# No password: key sign-in only. "*" (unlike "!") still allows key sign-in
# on servers whose sshd does not use PAM.
printf '%s:*\n' "$TAZMU_USER" | chpasswd -e >/dev/null 2>&1
if have usermod; then
  usermod -aG docker "$TAZMU_USER"
else
  addgroup "$TAZMU_USER" docker >/dev/null 2>&1 || true
fi
ok "can use Docker"

home=$(getent passwd "$TAZMU_USER" | cut -d: -f6)
[ -n "$home" ] && [ -d "$home" ] || die "could not find the home folder of $TAZMU_USER"
install -d -m 0700 -o "$TAZMU_USER" -g "$(id -gn "$TAZMU_USER")" "$home/.ssh"
keys="$home/.ssh/authorized_keys"
touch "$keys"
key_body=$(printf '%s' "$KEY" | cut -d' ' -f1-2)
# `restrict` turns off shells with a terminal, agent and X11 forwarding;
# port forwarding stays on because Tazmu's live desktop view uses it.
if grep -qF "$key_body" "$keys"; then
  ok "key already allowed"
else
  printf 'restrict,port-forwarding %s\n' "$KEY" >> "$keys"
  ok "key allowed"
fi
chown "$TAZMU_USER:$(id -gn "$TAZMU_USER")" "$keys"
chmod 0600 "$keys"

# ── 3. SSH ───────────────────────────────────────────────────────────────
say "SSH"
if have sshd || [ -x /usr/sbin/sshd ]; then
  start_service ssh 2>/dev/null || true
  start_service sshd 2>/dev/null || true
  ok "server installed"
else
  warn "no SSH server found. Install openssh-server so Tazmu can connect."
fi

# ── 4. Computer image ────────────────────────────────────────────────────
if [ "$PULL" = 1 ]; then
  say "Computer image"
  if docker pull "$IMAGE" >/dev/null 2>&1; then
    ok "pulled $IMAGE"
  else
    warn "could not pull $IMAGE now; Tazmu prepares it when a bot first uses this server"
  fi
fi

address=$(hostname -I 2>/dev/null | awk '{print $1}' || true)
printf '\n\033[1mDone.\033[0m In Tazmu, enter this server'"'"'s public IP address or host name.\n'
[ -n "$address" ] && printf 'This server reports %s (behind NAT, use the public address instead).\n' "$address"
return 0
}

main "$@"
