#!/bin/sh
# Installs Susan on this computer with Docker Compose, without cloning the repository:
#
#   curl -fsSL https://<site>/install.sh | sh
#
# It writes a Compose file to $SUSAN_HOME (default ~/.susan), pulls the images, starts the dashboard and the operator,
# and waits until the dashboard answers. Running it again updates the images and keeps your data (Docker volumes).
#
# Settings, all optional:
#   SUSAN_HOME     folder of the Compose file          default: ~/.susan
#   SUSAN_IMAGES   registry and prefix of the images   default: IMAGES_DEFAULT below
#   SUSAN_VERSION  image tag                           default: latest
#   SUSAN_PORT     port of the dashboard on 127.0.0.1  default: 8090
#   SUSAN_GVISOR   1 installs gVisor (runsc) and runs the containers of the runs under it; 0 turns it off.
#                  Default: 1 on Linux with Docker Engine, 0 on macOS and with Docker Desktop. An update keeps the
#                  choice of the previous install.
#   SUSAN_SUDO     command that gives root rights to install gVisor   default: sudo, else doas
#   FORGEJO_URL, FORGEJO_TOKEN, FORGEJO_WEBHOOK_SECRET  a Forgejo or Gitea forge to follow pull requests (optional)
set -eu

fail() {
  printf '\nSusan was not installed.\n%s\n' "$1" >&2
  exit 1
}

runsc_declared() {
  docker info --format '{{json .Runtimes}}' 2>/dev/null | grep -q '"runsc"'
}

# The package of a command for a package manager. Only the commands the gVisor install needs are listed.
package_of() {
  case "$2" in
    pkill) case "$1" in dnf | yum | pacman | xbps-install) echo procps-ng ;; *) echo procps ;; esac ;;
    sha512sum) echo coreutils ;;
    zstd) echo zstd ;;
  esac
}

# Installs the packages of the missing commands among the arguments, with the package manager of the distribution.
install_missing() {
  missing=""
  for cmd in "$@"; do
    command -v "$cmd" >/dev/null 2>&1 || missing="$missing $cmd"
  done
  [ -n "$missing" ] || return 0
  for manager in apk apt-get dnf yum zypper pacman xbps-install; do
    command -v "$manager" >/dev/null 2>&1 && break
    manager=""
  done
  [ -n "$manager" ] ||
    fail "gVisor needs these commands, which are missing:$missing, and this script knows no package manager on this system. Install them, then run this script again."
  packages=""
  for cmd in $missing; do
    packages="$packages $(package_of "$manager" "$cmd")"
  done
  printf 'Installing the packages gVisor needs with %s:%s...\n' "$manager" "$packages"
  # shellcheck disable=SC2086 # the package list splits on purpose
  case "$manager" in
    apk) $sudo apk add --no-cache $packages ;;
    apt-get) $sudo apt-get update -qq && $sudo env DEBIAN_FRONTEND=noninteractive apt-get install -y -qq $packages ;;
    dnf | yum) $sudo "$manager" install -y $packages ;;
    zypper) $sudo zypper --non-interactive install $packages ;;
    pacman) $sudo pacman -S --needed --noconfirm $packages ;;
    xbps-install) $sudo xbps-install -Sy $packages ;;
  esac || fail "$manager could not install$packages; the message above gives the cause. Install them yourself, then run this script again."
  for cmd in $missing; do
    command -v "$cmd" >/dev/null 2>&1 ||
      fail "$manager installed$packages, but $cmd is still missing. Install it yourself, then run this script again."
  done
}

# Installs gVisor from its signed release (https://gvisor.dev/docs/user_guide/install/) and declares it to Docker. A
# runsc already declared is kept as it is. Docker installed by snap runs confined and does not see /usr/local/bin of the
# host: gVisor then goes to the common folder of the snap, and is declared in the daemon.json of the snap.
install_gvisor() {
  if runsc_declared; then
    printf 'gVisor (runsc) is already declared to Docker.\n'
    return
  fi
  [ "$(uname -s)" = Linux ] ||
    fail "gVisor runs on Linux only. Run this script again with SUSAN_GVISOR=0."
  case "$(docker info --format '{{.OperatingSystem}} {{json .SecurityOptions}}')" in
    *"Docker Desktop"*) fail "Docker Desktop runs Docker in its own virtual machine, where this script cannot add gVisor. Use Docker Engine, or run this script again with SUSAN_GVISOR=0." ;;
    *rootless*) fail "Docker runs in rootless mode, and this script declares gVisor to the system Docker daemon only. Follow https://gvisor.dev/docs/user_guide/install/, or run this script again with SUSAN_GVISOR=0." ;;
  esac
  case "$(docker info --format '{{.DockerRootDir}}')" in
    /var/snap/docker/*)
      bindir=/var/snap/docker/common/gvisor
      config=/var/snap/docker/current/config/daemon.json
      printf 'Docker is installed by snap: gVisor goes to %s.\n' "$bindir" ;;
    *)
      bindir=/usr/local/bin
      config=/etc/docker/daemon.json ;;
  esac
  # The command that gives root rights: SUSAN_SUDO when set, else sudo, else doas (Alpine, OpenBSD-style systems).
  sudo=""
  if [ "$(id -u)" != 0 ]; then
    if [ -n "${SUSAN_SUDO:-}" ]; then sudo=$SUSAN_SUDO
    elif command -v sudo >/dev/null 2>&1; then sudo=sudo
    elif command -v doas >/dev/null 2>&1; then sudo=doas
    else fail "Installing gVisor needs root rights, and neither sudo nor doas is installed. Run this script as root, set SUSAN_SUDO to the command that gives you root rights, or run it again with SUSAN_GVISOR=0."
    fi
    command -v "$sudo" >/dev/null 2>&1 ||
      fail "SUSAN_SUDO names $sudo, which is not installed. Set SUSAN_SUDO to sudo or doas, then run this script again."
  fi

  runsc="$bindir/runsc"
  if [ "$bindir" = /usr/local/bin ] && command -v runsc >/dev/null 2>&1; then
    runsc=$(command -v runsc)
  fi
  # pkill reloads Docker; sha512sum checks the download and zstd unpacks it, when there is one. bzip2 is enough when
  # already there.
  if [ -x "$runsc" ]; then
    install_missing pkill
  elif command -v zstd >/dev/null 2>&1 || ! command -v bzip2 >/dev/null 2>&1; then
    install_missing pkill sha512sum zstd
  else
    install_missing pkill sha512sum
  fi
  if [ ! -x "$runsc" ]; then
    if command -v zstd >/dev/null 2>&1; then archive=gvisor.tar.zstd; unpack="zstd -dc"; else archive=gvisor.tar.bz2; unpack="bzip2 -dc"; fi
    url="https://storage.googleapis.com/gvisor/releases/release/latest/$(uname -m)"
    tmp=$(mktemp -d)
    trap 'rm -rf "$tmp"' EXIT
    printf 'Downloading gVisor from %s...\n' "$url"
    (cd "$tmp" && curl -fsSLO "$url/$archive" && curl -fsSLO "$url/$archive.sha512") ||
      fail "gVisor could not be downloaded from $url. Check your network, or that gVisor publishes a build for $(uname -m), then run this script again."
    (cd "$tmp" && sha512sum -c "$archive.sha512" >/dev/null) ||
      fail "The gVisor download does not match its checksum, so nothing was installed. Run this script again; if it fails again, install gVisor by hand from https://gvisor.dev/docs/user_guide/install/."
    printf 'Installing gVisor in %s (%s may ask for your password)...\n' "$bindir" "${sudo:-root}"
    { $sudo mkdir -p "$bindir" && $unpack "$tmp/$archive" | $sudo tar -xf - -C "$bindir"; } ||
      fail "gVisor could not be unpacked into $bindir. Check your rights on that folder, then run this script again."
  fi

  # runsc install adds the runtime to daemon.json; SIGHUP makes dockerd read it again without stopping containers, with
  # or without systemd.
  $sudo "$runsc" install --config_file="$config" >/dev/null ||
    fail "runsc could not declare itself to Docker in $config. Read the message above, then run this script again."
  $sudo pkill -HUP -x dockerd ||
    fail "gVisor is installed, but no running dockerd process received the reload signal. Restart Docker, then run this script again."
  tries=0
  until runsc_declared; do
    tries=$((tries + 1))
    [ "$tries" -lt 10 ] ||
      fail "gVisor is installed and declared in $config, but Docker does not list runsc after its reload. Restart Docker, then run this script again."
    sleep 1
  done
  printf 'gVisor (runsc) is declared to Docker.\n'
}

# The whole script runs from main, called on the last line: a download cut in the middle runs nothing.
main() {
  # ponytail: set when the images are published; until then SUSAN_IMAGES is required.
  IMAGES_DEFAULT=""

  SUSAN_HOME=${SUSAN_HOME:-"$HOME/.susan"}
  SUSAN_IMAGES=${SUSAN_IMAGES:-$IMAGES_DEFAULT}
  SUSAN_VERSION=${SUSAN_VERSION:-latest}
  SUSAN_PORT=${SUSAN_PORT:-8090}

  command -v docker >/dev/null 2>&1 ||
    fail "Docker is not installed on this computer. Install Docker Engine or Docker Desktop, then run this script again."
  docker info >/dev/null 2>&1 ||
    fail "Docker is installed but not reachable. Start Docker, check that your user can run 'docker info', then run this script again."
  docker compose version >/dev/null 2>&1 ||
    fail "Docker Compose v2 is missing: 'docker compose version' does not answer. Install the Compose plugin, then run this script again."
  command -v curl >/dev/null 2>&1 ||
    fail "curl is missing: this script uses it to check that the dashboard answers. Install curl, then run this script again."
  [ -n "$SUSAN_IMAGES" ] ||
    fail "No image registry is set. Set SUSAN_IMAGES to the registry and prefix of the Susan images, for example SUSAN_IMAGES=registry.example/susan, then run this script again."

  # gVisor is the default. An update keeps the isolation of the previous install; a new install on macOS or with Docker
  # Desktop goes without it, since the script cannot reach the virtual machine of Docker Desktop. SUSAN_GVISOR overrides.
  if [ -z "${SUSAN_GVISOR:-}" ]; then
    if [ -f "$SUSAN_HOME/.env" ]; then
      if grep -qx 'SUSAN_RUNTIME=runsc' "$SUSAN_HOME/.env"; then SUSAN_GVISOR=1; else SUSAN_GVISOR=0; fi
    elif [ "$(uname -s)" = Darwin ] || docker info --format '{{.OperatingSystem}}' 2>/dev/null | grep -q 'Docker Desktop'; then
      SUSAN_GVISOR=0
      printf 'Docker Desktop runs Docker in its own virtual machine: the runs use the default runtime of Docker, without gVisor.\n'
    else
      SUSAN_GVISOR=1
    fi
  fi
  SUSAN_RUNTIME=""
  if [ "${SUSAN_GVISOR:-0}" = 1 ]; then
    install_gvisor
    SUSAN_RUNTIME=runsc
  fi

  mkdir -p "$SUSAN_HOME"
  cd "$SUSAN_HOME"

  # The settings live in .env, so 'docker compose' run later from this folder finds them. The file may hold the forge
  # token: it is created readable by you alone, and an older copy gets the same permissions.
  previous_umask=$(umask)
  umask 077
  {
    printf 'SUSAN_IMAGES=%s\nSUSAN_VERSION=%s\nSUSAN_PORT=%s\nSUSAN_RUNTIME=%s\n' "$SUSAN_IMAGES" "$SUSAN_VERSION" "$SUSAN_PORT" "$SUSAN_RUNTIME"
    printf 'FORGEJO_URL=%s\nFORGEJO_TOKEN=%s\nFORGEJO_WEBHOOK_SECRET=%s\n' "${FORGEJO_URL:-}" "${FORGEJO_TOKEN:-}" "${FORGEJO_WEBHOOK_SECRET:-local}"
  } > .env
  chmod 600 .env
  umask "$previous_umask"

  cat > compose.yaml <<'COMPOSE'
# Written by the Susan install script. Run it again to update; edit .env for the settings.
name: susan

services:
  # The image of the runs. The operator starts one container of it per run; this service only pulls it.
  runner:
    image: ${SUSAN_IMAGES}/nexus-runner:${SUSAN_VERSION}
    entrypoint: ["true"]
    restart: "no"

  # Creates once the key that signs the run tokens and the token of the operator API.
  keys:
    image: ${SUSAN_IMAGES}/nexus-runner:${SUSAN_VERSION}
    depends_on: { runner: { condition: service_completed_successfully } }
    user: "0:0"
    entrypoint: ["sh", "-c"]
    command:
      - |
        set -e
        for name in token-key api-token; do
          [ -s /keys/$$name ] || head -c 48 /dev/urandom | base64 -w0 > /keys/$$name
        done
        chmod 0444 /keys/token-key /keys/api-token
        chown 65532:65532 /dashboard-data
    volumes: [keys:/keys, dashboard-data:/dashboard-data]
    restart: "no"

  # The operator starts each run in a container through the Docker socket of this computer.
  operator:
    image: ${SUSAN_IMAGES}/nexus-operator:${SUSAN_VERSION}
    depends_on: { keys: { condition: service_completed_successfully } }
    user: "0:0"
    restart: unless-stopped
    environment:
      NEXUS_OPERATOR_ENGINE: docker
      NEXUS_OPERATOR_DATABASE: /data/operator.db
      NEXUS_OPERATOR_RUNNER_IMAGE: ${SUSAN_IMAGES}/nexus-runner:${SUSAN_VERSION}
      NEXUS_OPERATOR_DOCKER_NETWORK: susan
      # runsc runs the containers of the runs under gVisor; empty keeps the default runtime of Docker.
      NEXUS_OPERATOR_DOCKER_RUNTIME: ${SUSAN_RUNTIME:-}
      NEXUS_OPERATOR_ENDPOINT: operator:7443
      NEXUS_OPERATOR_PROJECTS: local
      NEXUS_OPERATOR_DASHBOARD_URL: http://dashboard:8090
      NEXUS_OPERATOR_TOKEN_KEY_FILE: /keys/token-key
      NEXUS_OPERATOR_API_TOKEN_FILE: /keys/api-token
    volumes:
      - /var/run/docker.sock:/var/run/docker.sock
      - keys:/keys:ro
      - operator-data:/data

  dashboard:
    image: ${SUSAN_IMAGES}/nexus-dashboard:${SUSAN_VERSION}
    depends_on: { operator: { condition: service_started }, keys: { condition: service_completed_successfully } }
    restart: unless-stopped
    ports: ["127.0.0.1:${SUSAN_PORT}:8090"]
    environment:
      NEXUS_DASHBOARD_DB: /data/dashboard.db
      NEXUS_DASHBOARD_BASE_URL: http://localhost:${SUSAN_PORT}
      NEXUS_OPERATOR_URL: http://operator:8443
      NEXUS_OPERATOR_PLAINTEXT: "true"
      NEXUS_OPERATOR_API_TOKEN_FILE: /keys/api-token
      NEXUS_OPERATOR_TOKEN_KEY_FILE: /keys/token-key
      FORGEJO_URL: ${FORGEJO_URL}
      FORGEJO_TOKEN: ${FORGEJO_TOKEN}
      FORGEJO_WEBHOOK_SECRET: ${FORGEJO_WEBHOOK_SECRET}
    volumes:
      - keys:/keys:ro
      - dashboard-data:/data

networks:
  default:
    name: susan

volumes:
  keys:
  operator-data:
  dashboard-data:
COMPOSE

  printf 'Pulling the Susan images (%s, version %s)...\n' "$SUSAN_IMAGES" "$SUSAN_VERSION"
  if ! docker compose pull --quiet; then
    # Already present images (a reinstall without network, images loaded by hand) are enough to start.
    for name in nexus-runner nexus-operator nexus-dashboard; do
      docker image inspect "$SUSAN_IMAGES/$name:$SUSAN_VERSION" >/dev/null 2>&1 ||
        fail "The images could not be pulled from $SUSAN_IMAGES, and $name:$SUSAN_VERSION is not on this computer. Check the registry address and your network, then run this script again."
    done
    printf 'The registry did not answer; the images already on this computer are used.\n'
  fi
  # Declared is not enough: a confined Docker (snap) or an SELinux policy can still refuse to start runsc. One container
  # of the runner image proves it before any run depends on it.
  if [ -n "$SUSAN_RUNTIME" ]; then
    docker run --rm --runtime=runsc --entrypoint true "$SUSAN_IMAGES/nexus-runner:$SUSAN_VERSION" ||
      fail "Docker declares gVisor (runsc) but cannot start a container with it; the message above gives the cause. Install gVisor by hand from https://gvisor.dev/docs/user_guide/install/, or run this script again with SUSAN_GVISOR=0."
  fi
  docker compose up -d --remove-orphans ||
    fail "The containers did not start. Read 'docker compose logs' in $SUSAN_HOME for the cause, then run this script again."

  printf 'Waiting for the dashboard...\n'
  tries=0
  until curl -fsS -o /dev/null "http://127.0.0.1:$SUSAN_PORT/" 2>/dev/null; do
    tries=$((tries + 1))
    [ "$tries" -lt 60 ] ||
      fail "The containers run, but the dashboard did not answer on port $SUSAN_PORT within 60 seconds. Read 'docker compose logs dashboard' in $SUSAN_HOME for the cause."
    sleep 1
  done

  printf '\nSusan is running on http://localhost:%s\n' "$SUSAN_PORT"
  if [ -n "$SUSAN_RUNTIME" ]; then
    printf 'The containers of the runs run under gVisor (runsc).\n'
  fi
  printf 'Files and settings: %s\n' "$SUSAN_HOME"
  printf 'To stop it:   cd %s && docker compose down\n' "$SUSAN_HOME"
  printf 'To remove it: cd %s && docker compose down -v, then delete the folder\n' "$SUSAN_HOME"
}

main "$@"
