#!/usr/bin/env bash
# koko server installer (Bun implementation), Debian only for now.
#
#   curl -fsSL https://kokoz.pages.dev/install.sh | sudo bash
#
# What it does, in order:
#   1. checks this is Debian (or a Debian derivative) running systemd, as root
#   2. installs curl, unzip and ca-certificates with apt if they are missing
#   3. installs Bun into /opt/koko/bun, unless a Bun the service user can run is already installed
#   4. downloads the source of the latest koko release and keeps koko-server-bun/src
#   5. creates a "koko" system user (before step 3), /var/lib/koko for the database, /etc/koko.env for settings
#   6. installs and starts a systemd service named koko, so it survives reboots
#   7. installs /opt/koko/update.sh and a systemd timer that runs it every night, so the server
#      keeps itself on the latest release (turn that off with KOKO_AUTOUPDATE=0, see below)
#   8. prints the server link
#
# Updates: the timer (koko-update.timer, about 04:30 plus up to an hour of random delay) checks the
# latest release, and only when it is newer swaps the new files in, restarts the server (a second or
# two of downtime), checks /healthz, and puts the previous version back if the new one does not come up.
# Update right now with:  sudo /opt/koko/update.sh      See what it did:  journalctl -u koko-update
# Running this installer again also updates. Your database and /etc/koko.env are kept. Remove everything with:
#   sudo systemctl disable --now koko koko-update.timer && sudo rm -rf /opt/koko /etc/systemd/system/koko.service /etc/systemd/system/koko-update.* /etc/koko.env
# (the database in /var/lib/koko stays until you delete it yourself).
#
# Settings (set them before the command, after sudo):
#   KOKO_PORT=8080   port to listen on, first install only (default: first free port from 8080)
#   KOKO_AUTOUPDATE=0  no nightly updates (update by hand with /opt/koko/update.sh); 1 turns them back on.
#                      Left unset, a first install turns them on and a rerun keeps what you chose before.
#
# Why source and not a binary: the Bun server is a few TypeScript files with no
# dependencies, so the release tarball is all it needs. The canonical server is
# the Rust one (koko-server-linux-x86_64 on the releases page); this installer is
# for people who prefer the Bun one.
set -euo pipefail

REPO="74mdi/koko"
DIR=/opt/koko
DATA=/var/lib/koko
ENVFILE=/etc/koko.env
UNIT=/etc/systemd/system/koko.service
PORT="${KOKO_PORT:-}"
AUTO="${KOKO_AUTOUPDATE:-}"

say() { printf '\033[1m==> %s\033[0m\n' "$*"; }
die() { printf 'error: %s\n' "$*" >&2; exit 1; }

[ "$(id -u)" -eq 0 ] || die "run as root: curl -fsSL https://kokoz.pages.dev/install.sh | sudo bash"
[ "$(uname -s)" = Linux ] || die "Linux only"
case "$(uname -m)" in x86_64 | aarch64) ;; *) die "unsupported CPU $(uname -m) (Bun needs x86_64 or aarch64)" ;; esac
. /etc/os-release 2>/dev/null || die "cannot read /etc/os-release"
case " ${ID:-} ${ID_LIKE:-} " in *" debian "*) ;; *) die "Debian only for now (this is ${PRETTY_NAME:-unknown})" ;; esac
[ -d /run/systemd/system ] || die "systemd is not running here"
case "$PORT" in *[!0-9]*) die "KOKO_PORT must be a number" ;; esac
case "$AUTO" in "" | 0 | 1) ;; *) die "KOKO_AUTOUPDATE must be 0 or 1" ;; esac

say "Installing prerequisites"
need=""
for c in curl unzip tar; do command -v "$c" >/dev/null || need="$need $c"; done
[ -e /etc/ssl/certs/ca-certificates.crt ] || need="$need ca-certificates"
if [ -n "$need" ]; then
  apt-get update -qq
  # shellcheck disable=SC2086
  DEBIAN_FRONTEND=noninteractive apt-get install -y -qq $need >/dev/null
fi

# Download with a progress bar. Gives up if the connection takes over 15 s, or if
# the speed stays under 10 KB/s for 30 s, so a bad network fails instead of hanging.
fetch() {
  curl -fL --progress-bar --connect-timeout 15 --speed-limit 10000 --speed-time 30 --retry 3 --retry-delay 2 -o "$2" "$1"
}

# Bun comes from its GitHub release (what bun.sh itself uses), and from the npm
# registry as a fallback. Both are the official build; no installer script is run.
install_bun() {
  local arch pkg url t
  case "$(uname -m)" in
    x86_64) arch=x64; grep -qw avx2 /proc/cpuinfo || arch=x64-baseline ;;
    aarch64) arch=aarch64 ;;
  esac
  t=$(mktemp -d)
  if fetch "https://github.com/oven-sh/bun/releases/latest/download/bun-linux-$arch.zip" "$t/bun.zip"; then
    unzip -q "$t/bun.zip" -d "$t"
    mkdir -p "$DIR/bun/bin"
    install -m 0755 "$t/bun-linux-$arch/bun" "$DIR/bun/bin/bun"
  else
    say "GitHub download failed, trying the npm registry"
    pkg="@oven/bun-linux-$arch"
    url=$(curl -fsS --connect-timeout 15 --max-time 30 "https://registry.npmjs.org/$pkg/latest" | grep -o '"tarball":"[^"]*"' | head -n 1 | cut -d'"' -f4) || true
    [ -n "$url" ] || { rm -rf "$t"; die "could not download Bun from GitHub or npm; check your internet connection"; }
    fetch "$url" "$t/bun.tgz" || { rm -rf "$t"; die "could not download Bun; check your internet connection"; }
    tar -xzf "$t/bun.tgz" -C "$t"
    mkdir -p "$DIR/bun/bin"
    install -m 0755 "$t/package/bin/bun" "$DIR/bun/bin/bun"
  fi
  rm -rf "$t"
}

# The service runs as the koko user, so a Bun is only reusable if that user can run it.
id koko >/dev/null 2>&1 || useradd --system --home-dir "$DATA" --shell /usr/sbin/nologin koko
BUN=""
for c in "$DIR/bun/bin/bun" "$(command -v bun || true)"; do
  case "$c" in "" | /home/* | /root/*) continue ;; esac
  if runuser -u koko -- "$c" --version >/dev/null 2>&1; then BUN=$c; break; fi
done
if [ -n "$BUN" ]; then
  say "Using the Bun that is already installed ($BUN $("$BUN" --version))"
else
  say "Installing Bun (about 40 MB)"
  install_bun
  BUN="$DIR/bun/bin/bun"
  runuser -u koko -- "$BUN" --version >/dev/null 2>&1 || die "bun did not install"
fi

say "Setting up the service"
install -d -o koko -g koko -m 0750 "$DATA"
if [ ! -f "$ENVFILE" ]; then
  if [ -z "$PORT" ]; then
    # Take the first free port from 8080 up, so an existing service is never fought over.
    PORT=8080
    while ss -ltn 2>/dev/null | awk '{print $4}' | grep -q ":$PORT\$"; do PORT=$((PORT + 1)); done
  fi
  cat >"$ENVFILE" <<EOF
KOKO_BIND=0.0.0.0:$PORT
KOKO_DB=$DATA/koko.db
# Set to 1 only when a reverse proxy you control sits in front of the server.
KOKO_TRUST_PROXY=0
# KOKO_CORS_ORIGIN=
EOF
fi
cat >"$UNIT" <<EOF
[Unit]
Description=koko server (Bun)
After=network-online.target
Wants=network-online.target

[Service]
User=koko
Group=koko
EnvironmentFile=$ENVFILE
WorkingDirectory=$DIR/app
ExecStart=$BUN src/main.ts
Restart=on-failure
RestartSec=2
NoNewPrivileges=true
ProtectSystem=strict
ProtectHome=true
PrivateTmp=true
ReadWritePaths=$DATA

[Install]
WantedBy=multi-user.target
EOF
# update.sh does the download, the swap, the restart and the health check. The installer and the nightly
# timer both run it, so there is one code path to trust.
cat >"$DIR/update.sh" <<'UPD'
#!/usr/bin/env bash
# Moves the koko server to the latest release. Run by koko-update.timer, or by hand: sudo /opt/koko/update.sh
# --force reinstalls even when the version is already the latest.
set -euo pipefail
REPO="74mdi/koko"
DIR=/opt/koko
ENVFILE=/etc/koko.env
say() { printf '==> %s\n' "$*"; }
die() { printf 'error: %s\n' "$*" >&2; exit 1; }
[ "$(id -u)" -eq 0 ] || die "run as root: sudo $0"

fetch() {
  curl -fL --progress-bar --connect-timeout 15 --speed-limit 10000 --speed-time 30 --retry 3 --retry-delay 2 -o "$2" "$1"
}
healthy() {
  local bind port
  bind=$(sed -n 's/^KOKO_BIND=//p' "$ENVFILE" | tail -n 1)
  port=${bind##*:}
  for _ in 1 2 3 4 5 6 7 8 9 10; do
    if systemctl is-active --quiet koko && curl -fsS -o /dev/null "http://127.0.0.1:$port/healthz" 2>/dev/null; then return 0; fi
    sleep 1
  done
  return 1
}

TAG=$(curl -fsSIL --connect-timeout 15 --max-time 30 -o /dev/null -w '%{url_effective}' "https://github.com/$REPO/releases/latest")
TAG=${TAG##*/}
case "$TAG" in v[0-9]*) ;; *) die "could not find the latest release ($TAG)" ;; esac
cur=$(cat "$DIR/version" 2>/dev/null || true)
if [ "$TAG" = "$cur" ] && [ "${1:-}" != "--force" ] && [ -f "$DIR/app/src/main.ts" ]; then
  say "koko $cur is already the latest"
  exit 0
fi

say "Downloading koko $TAG${cur:+ (running $cur)}"
tmp=$(mktemp -d)
trap 'rm -rf "$tmp"' EXIT
fetch "https://github.com/$REPO/archive/refs/tags/$TAG.tar.gz" "$tmp/src.tgz" || die "could not download release $TAG"
tar -xzf "$tmp/src.tgz" -C "$tmp" --wildcards '*/koko-server-bun/src' '*/koko-server-bun/package.json'
srv=$(echo "$tmp"/*/koko-server-bun)
[ -f "$srv/src/main.ts" ] || die "release $TAG has no Bun server"

# Stage next to the live copy, then swap with two renames, so the server only stops for the restart.
rm -rf "$DIR/app.new" "$DIR/app.prev"
mkdir -p "$DIR/app.new"
cp -r "$srv/src" "$srv/package.json" "$DIR/app.new/"
[ ! -d "$DIR/app" ] || mv "$DIR/app" "$DIR/app.prev"
mv "$DIR/app.new" "$DIR/app"
echo "$TAG" >"$DIR/version"

say "Restarting"
systemctl restart koko
if healthy; then
  say "koko $TAG is running"
  exit 0
fi
journalctl -u koko -n 20 --no-pager >&2 || true
if [ -d "$DIR/app.prev" ]; then
  say "$TAG did not come up, putting ${cur:-the previous version} back"
  rm -rf "$DIR/app"
  mv "$DIR/app.prev" "$DIR/app"
  echo "$cur" >"$DIR/version"
  systemctl restart koko
  healthy && die "$TAG failed its health check, rolled back to ${cur:-the previous version}"
fi
die "the server did not come up, see the log above"
UPD
chmod 0755 "$DIR/update.sh"

cat >/etc/systemd/system/koko-update.service <<EOF
[Unit]
Description=Update the koko server to the latest release
After=network-online.target
Wants=network-online.target

[Service]
Type=oneshot
ExecStart=$DIR/update.sh
EOF
cat >/etc/systemd/system/koko-update.timer <<EOF
[Unit]
Description=Nightly koko server update check

[Timer]
OnCalendar=*-*-* 04:30:00
RandomizedDelaySec=1h
Persistent=true

[Install]
WantedBy=timers.target
EOF

# 1, or unset on a first install: on. 0: off, remembered so a later rerun does not turn it back on.
[ "$AUTO" != 0 ] || touch "$DIR/no-autoupdate"
[ "$AUTO" != 1 ] || rm -f "$DIR/no-autoupdate"
systemctl daemon-reload
systemctl enable koko >/dev/null 2>&1
if [ -e "$DIR/no-autoupdate" ]; then
  systemctl disable --now koko-update.timer >/dev/null 2>&1 || true
else
  systemctl enable --now koko-update.timer >/dev/null 2>&1
fi
say "Downloading and starting the latest koko release"
"$DIR/update.sh" --force
TAG=$(cat "$DIR/version")

bind=$(sed -n 's/^KOKO_BIND=//p' "$ENVFILE" | tail -n 1)
port=${bind##*:}

host=$(curl -4 -fsS --connect-timeout 5 --max-time 8 https://api.ipify.org 2>/dev/null || true)
[ -n "$host" ] || host=$(hostname -I 2>/dev/null | awk '{print $1}')
[ -n "$host" ] || host=localhost

printf '\n\033[1mkoko server %s is running.\033[0m\n\n' "$TAG"
printf '  Server link:  http://%s:%s\n\n' "$host" "$port"
printf '  Paste it into the koko app as the server address.\n'
printf '  It is plain http. Put it behind HTTPS (a reverse proxy) before real use,\n'
printf '  and open port %s in your firewall if you cannot reach it.\n' "$port"
if [ -e "$DIR/no-autoupdate" ]; then
  printf '  Updates: manual, run  sudo %s/update.sh  (nightly updates are off)\n' "$DIR"
else
  printf '  Updates: automatic, every night. Update now: sudo %s/update.sh\n' "$DIR"
fi
printf '  Manage:  systemctl status koko   journalctl -u koko -f   settings: %s\n' "$ENVFILE"
