#!/usr/bin/env bash
#
# Notakey Authentication Appliance - installer bootstrap
#
#   sudo bash -c "$(curl -fsSL https://www.notakey.com/install/appliance.sh)"
#
# Read it before you run it:
#
#   curl -fsSL https://www.notakey.com/install/appliance.sh | less
#
# What this script does, in order:
#   1. Checks that it runs as root, on x86-64, in a terminal.
#   2. Installs Docker Engine from Docker's own apt repository if Docker is
#      not there yet (Debian and Ubuntu only; elsewhere install Docker first).
#   3. On Docker Engine 28 or newer, sets "min-api-version": "1.24" in
#      /etc/docker/daemon.json and restarts Docker. The appliance's built-in
#      reverse proxy talks to Docker with that API version and finds no
#      services without it.
#   4. Disables cloud-init if it is present, so a later reboot does not reset
#      the hostname and network settings the appliance relies on.
#   5. Starts the Notakey installer container (notakey/cfg), which installs the
#      "ntk" management command and walks you through the configuration wizard.
#
# It does not open firewall ports, create users or change SSH settings.
#
# Running it again on a machine that already has the appliance is the way to
# repair or reinstall the management tools: it says what it found and asks
# before going on. There is no uninstall mode.
#
# Optional environment variables:
#   NOTAKEY_YES=1            do not ask for confirmation before starting
#   NOTAKEY_REINSTALL=1      also do not ask before running over an existing
#                            installation (NOTAKEY_YES alone still asks)
#   NOTAKEY_SKIP_DOCKER=1    never install Docker, fail if it is missing
#   NOTAKEY_CFG_IMAGE=...    installer image (default: notakey/cfg:latest)
#
# Manual steps this replaces:
#   https://www.notakey.com/support/kb/install-appliance-on-ubuntu/

set -euo pipefail

CFG_IMAGE="${NOTAKEY_CFG_IMAGE:-notakey/cfg:latest}"

say()  { printf '==> %s\n' "$*"; }
note() { printf '    %s\n' "$*"; }
warn() { printf 'WARNING: %s\n' "$*" >&2; }
die()  { printf 'ERROR: %s\n' "$*" >&2; exit 1; }

confirm() {
  # confirm "question" -> returns 0 on yes
  local answer
  if [ "${NOTAKEY_YES:-0}" = "1" ]; then
    return 0
  fi
  read -r -p "$1 [y/N] " answer
  case "$answer" in
    y | Y | yes | YES) return 0 ;;
    *) return 1 ;;
  esac
}

# --- 1. Preconditions --------------------------------------------------------

[ "$(id -u)" -eq 0 ] || die "run this as root, for example:
  sudo bash -c \"\$(curl -fsSL https://www.notakey.com/install/appliance.sh)\""

if [ ! -t 0 ] || [ ! -t 1 ]; then
  die "the configuration wizard needs a terminal. Do not pipe this script into
  bash; run it like this instead:
  sudo bash -c \"\$(curl -fsSL https://www.notakey.com/install/appliance.sh)\""
fi

arch="$(uname -m)"
[ "$arch" = "x86_64" ] || die "unsupported CPU architecture '$arch': the appliance images are built for x86-64 only."

os_id="unknown"
os_codename=""
os_name="unknown Linux"
if [ -r /etc/os-release ]; then
  # shellcheck disable=SC1091
  . /etc/os-release
  os_id="${ID:-unknown}"
  os_codename="${VERSION_CODENAME:-}"
  os_name="${PRETTY_NAME:-$os_id}"
fi

mem_mb="$(awk '/^MemTotal:/ {print int($2 / 1024)}' /proc/meminfo 2>/dev/null || echo 0)"
disk_gb="$(df -Pk / 2>/dev/null | awk 'NR == 2 {print int($4 / 1024 / 1024)}' || echo 0)"

say "Notakey Authentication Appliance installer"
note "System:       $os_name ($arch)"
note "Memory:       ${mem_mb} MB"
note "Free on /:    ${disk_gb} GB"
note "Installer:    $CFG_IMAGE"

if [ "$mem_mb" -gt 0 ] && [ "$mem_mb" -lt 1900 ]; then
  warn "less than 2 GB of memory. The appliance starts with 1 GB, but leave room for growth."
fi
if [ "$disk_gb" -gt 0 ] && [ "$disk_gb" -lt 10 ]; then
  warn "less than 10 GB free on /. The appliance images alone need several GB."
fi
if command -v systemd-detect-virt >/dev/null 2>&1 &&
  [ "$(systemd-detect-virt --container 2>/dev/null || true)" = "lxc" ]; then
  note "Running in an LXC container: Docker needs the container's 'nesting' feature."
fi
existing=0
if [ -f /opt/notakey/cfg/.env ]; then
  existing=1
fi

have_docker=0
if command -v docker >/dev/null 2>&1; then
  have_docker=1
  note "Docker:       $(docker --version 2>/dev/null || echo present)"
else
  note "Docker:       not installed"
fi

install_docker=0
if [ "$have_docker" -eq 0 ]; then
  if [ "${NOTAKEY_SKIP_DOCKER:-0}" = "1" ]; then
    die "Docker is not installed and NOTAKEY_SKIP_DOCKER=1 is set."
  fi
  case "$os_id" in
    debian | ubuntu)
      [ -n "$os_codename" ] || die "cannot read the release codename from /etc/os-release; install Docker manually: https://docs.docker.com/engine/install/"
      install_docker=1
      ;;
    *)
      die "Docker is not installed and this script only installs it on Debian and Ubuntu.
  Install Docker Engine first (https://docs.docker.com/engine/install/), then run this script again."
      ;;
  esac
fi

if [ "$existing" -eq 1 ]; then
  echo
  say "An appliance is already installed on this machine"
  note "Found:        /opt/notakey/cfg/.env"
  if [ "$have_docker" -eq 1 ]; then
    running="$(docker ps --format '{{.Names}}' 2>/dev/null | tr '\n' ' ' || true)"
    note "Running:      ${running:-no containers}"
  fi
  note "Continuing runs the Notakey installer again over it: the management"
  note "tools ('ntk') are reinstalled and the current packages are downloaded."
  note "The installer asks two questions. 'Do you wish to continue?' - answer"
  note "'y' to reinstall. 'Do you wish to run configuration wizard?' - answer"
  note "'n' to keep the configuration you have."
  note "For day-to-day changes and updates use 'ntk' instead ('ntk sys update')."
  if [ "${NOTAKEY_REINSTALL:-0}" != "1" ]; then
    echo
    NOTAKEY_YES=0 confirm "Run the installer over the existing installation?" || die "aborted, nothing was changed."
  fi
fi

echo
say "This will:"
[ "$install_docker" -eq 1 ] && note "- install Docker Engine from download.docker.com (apt repository)"
if [ -d /etc/cloud ] && [ ! -e /etc/cloud/cloud-init.disabled ]; then
  note "- disable cloud-init (creates /etc/cloud/cloud-init.disabled)"
fi
note "- on Docker Engine 28 or newer: set \"min-api-version\": \"1.24\" in"
note "  /etc/docker/daemon.json and restart Docker (skipped if already set)"
note "- pull $CFG_IMAGE and start the Notakey installation wizard"
echo
if [ "$existing" -eq 0 ]; then
  confirm "Continue?" || die "aborted, nothing was changed."
fi

# --- 2. Docker ---------------------------------------------------------------

if [ "$install_docker" -eq 1 ]; then
  say "Installing Docker Engine"
  export DEBIAN_FRONTEND=noninteractive
  apt-get update -qq
  apt-get install -y -qq ca-certificates curl >/dev/null
  install -m 0755 -d /etc/apt/keyrings
  curl -fsSL "https://download.docker.com/linux/${os_id}/gpg" -o /etc/apt/keyrings/docker.asc
  chmod a+r /etc/apt/keyrings/docker.asc
  printf 'deb [arch=%s signed-by=/etc/apt/keyrings/docker.asc] https://download.docker.com/linux/%s %s stable\n' \
    "$(dpkg --print-architecture)" "$os_id" "$os_codename" >/etc/apt/sources.list.d/docker.list
  apt-get update -qq
  apt-get install -y -qq docker-ce docker-ce-cli containerd.io >/dev/null
  note "$(docker --version)"
fi

if command -v systemctl >/dev/null 2>&1; then
  systemctl enable --now docker >/dev/null 2>&1 || true
fi
docker info >/dev/null 2>&1 || die "Docker is installed but the daemon is not answering ('docker info' failed).
  In an LXC container, check that the 'nesting' feature is enabled."

if [ -n "${SUDO_USER:-}" ] && [ "$SUDO_USER" != "root" ] && getent group docker >/dev/null 2>&1; then
  usermod -aG docker "$SUDO_USER" || true
  note "Added $SUDO_USER to the docker group (takes effect at the next login)."
fi

# --- 3. Docker API version ---------------------------------------------------

# Docker Engine 28+ refuses API clients older than 1.40 by default. The
# appliance's reverse proxy uses API 1.24; without this setting it cannot see
# the services and answers 404.
api_too_new() {
  local min
  min="$(docker version --format '{{.Server.MinAPIVersion}}' 2>/dev/null || true)"
  [ -n "$min" ] && [ "$(printf '%s\n' "$min" 1.24 | sort -V | head -n 1)" != "$min" ]
}

if api_too_new; then
  say "Setting Docker's minimum API version to 1.24"
  daemon_json=/etc/docker/daemon.json
  manual_hint="add  \"min-api-version\": \"1.24\"  to $daemon_json, run 'systemctl restart docker', then run this script again."
  if [ ! -s "$daemon_json" ]; then
    mkdir -p /etc/docker
    printf '{\n  "min-api-version": "1.24"\n}\n' >"$daemon_json"
  elif command -v python3 >/dev/null 2>&1; then
    cp -p "$daemon_json" "$daemon_json.notakey-backup"
    python3 - "$daemon_json" <<'PY' || die "could not update /etc/docker/daemon.json (is it valid JSON?). By hand: $manual_hint"
import json, sys
path = sys.argv[1]
with open(path) as f:
    cfg = json.load(f)
cfg["min-api-version"] = "1.24"
with open(path, "w") as f:
    json.dump(cfg, f, indent=2)
    f.write("\n")
PY
    note "Previous file kept as $daemon_json.notakey-backup"
  else
    die "$daemon_json already exists and python3 is not available to edit it. By hand: $manual_hint"
  fi
  if [ "$existing" -eq 1 ]; then
    note "Restarting Docker; the appliance's services restart with it."
  fi
  systemctl restart docker 2>/dev/null || service docker restart
  for _ in $(seq 1 30); do
    docker info >/dev/null 2>&1 && break
    sleep 1
  done
  api_too_new && die "Docker still refuses API 1.24 after the restart. By hand: $manual_hint"
  note "Docker now accepts API $(docker version --format '{{.Server.MinAPIVersion}}') and newer."
fi

# --- 4. cloud-init -----------------------------------------------------------

if [ -d /etc/cloud ] && [ ! -e /etc/cloud/cloud-init.disabled ]; then
  say "Disabling cloud-init"
  touch /etc/cloud/cloud-init.disabled
  note "Created /etc/cloud/cloud-init.disabled. It takes effect at the next reboot."
fi

# --- 5. Notakey installer ----------------------------------------------------

say "Pulling $CFG_IMAGE"
docker pull "$CFG_IMAGE"

say "Starting the Notakey installation wizard"
docker run --rm -it \
  --privileged \
  --net=host \
  -e NTK_USER=root \
  -v /var/run/docker.sock:/var/run/docker.sock:rw \
  -v /:/appliancehost \
  "$CFG_IMAGE" install

echo
if [ ! -f /opt/notakey/cfg/.env ]; then
  say "The wizard ended without installing the appliance"
  note "Nothing was configured. Run this script again when you are ready."
  exit 0
fi
if [ "$existing" -eq 1 ]; then
  say "The installer has ended"
  note "If you stopped it at its first question, nothing was changed."
  note "Check the appliance with: ntk as status"
  exit 0
fi
say "Installer finished"
note "Manage the appliance with the 'ntk' command (open a new shell if it is not found)."
note "Configuration reference: https://documentation.notakey.com/cli/"
note "First phone approval:    https://www.notakey.com/blog/first-phone-approval-from-zero/"
