#!/bin/sh
# Requestarium self-hosted: one-line install, upgrade and uninstall with Docker Compose.
#
#   curl -fsSL https://get.requestarium.com | sh
#   curl -fsSL https://get.requestarium.com | sh -s -- --domain requestarium.example.com
#
# Options (after `sh -s --` when piped):
#   --domain <name>     serve https://<name> with Let's Encrypt on ports 80/443 (a server with public DNS).
#                       Without it: a local trial on http://localhost:<port>, reachable from this machine only.
#   --port <port>       local trial port (default 8080)
#   --dir <path>        install directory (default /opt/requestarium as root, ~/requestarium otherwise)
#   --version <x.y.z>   install or upgrade to this release (default: the latest release)
#   --admin-email <e>   installation administrator(s), comma separated (default: the first account that signs up)
#   --yes               do not ask before upgrading or uninstalling (needed when there is no terminal)
#   --dry-run           check and download, but only print what would be changed or run
#   --uninstall         stop and remove the containers; data volumes and the directory stay
#   --purge             with --uninstall: also delete the database, backups and the install directory
#   -h, --help          this text
#
# Running it again on an installed directory upgrades it to the latest (or --version) release: the release files
# are refreshed, .env and certs/ are kept, and ./upgrade.sh takes a database backup before switching versions.
#
# Environment: REQUESTARIUM_DOWNLOADS_URL (default https://downloads.requestarium.com/self-hosted) to use a mirror.
#
# Docs: https://github.com/NickTaporuk/tairi/blob/develop/docs/self-hosted/quick-install.md

# Everything is inside main(), called on the last line, so a download cut off half-way runs nothing.
main() {
  set -eu

  DOWNLOADS="${REQUESTARIUM_DOWNLOADS_URL:-https://downloads.requestarium.com/self-hosted}"
  DOWNLOADS="${DOWNLOADS%/}"
  DOMAIN=""
  PORT=8080
  DIR=""
  VERSION=""
  ADMIN_EMAILS=""
  ASSUME_YES=false
  DRY_RUN=false
  ACTION=install
  PURGE=false

  while [ $# -gt 0 ]; do
    case "$1" in
      --domain) need_value "$@"; DOMAIN=$2; shift 2 ;;
      --domain=*) DOMAIN=${1#*=}; shift ;;
      --port) need_value "$@"; PORT=$2; shift 2 ;;
      --port=*) PORT=${1#*=}; shift ;;
      --dir) need_value "$@"; DIR=$2; shift 2 ;;
      --dir=*) DIR=${1#*=}; shift ;;
      --version) need_value "$@"; VERSION=${2#v}; shift 2 ;;
      --version=*) VERSION=${1#*=}; VERSION=${VERSION#v}; shift ;;
      --admin-email) need_value "$@"; ADMIN_EMAILS=$2; shift 2 ;;
      --admin-email=*) ADMIN_EMAILS=${1#*=}; shift ;;
      --yes | -y) ASSUME_YES=true; shift ;;
      --dry-run) DRY_RUN=true; shift ;;
      --uninstall) ACTION=uninstall; shift ;;
      --purge) PURGE=true; shift ;;
      -h | --help) usage; exit 0 ;;
      *) die "unknown option: $1 (see --help)" ;;
    esac
  done

  if [ -n "$DOMAIN" ]; then
    printf '%s' "$DOMAIN" | grep -Eq '^[A-Za-z0-9]([A-Za-z0-9.-]*[A-Za-z0-9])?$' || die "--domain must be a host name like requestarium.example.com"
    case "$DOMAIN" in *.*) ;; *) die "--domain must be a public host name (leave it out for a local trial)" ;; esac
  fi
  printf '%s' "$PORT" | grep -Eq '^[0-9]{2,5}$' && [ "$PORT" -ge 1 ] && [ "$PORT" -le 65535 ] || die "--port must be a TCP port"
  [ -z "$VERSION" ] || printf '%s' "$VERSION" | grep -Eq '^[0-9]+\.[0-9]+\.[0-9]+$' || die "--version must look like 1.2.3"
  [ -z "$ADMIN_EMAILS" ] || printf '%s' "$ADMIN_EMAILS" | grep -Eq '^[^[:space:]@,]+@[^[:space:]@,]+(,[^[:space:]@,]+@[^[:space:]@,]+)*$' \
    || die "--admin-email must be one or more emails separated by commas"
  [ "$PURGE" = false ] || [ "$ACTION" = uninstall ] || die "--purge only goes with --uninstall"

  if [ -z "$DIR" ]; then
    if [ "$(id -u)" = 0 ]; then DIR=/opt/requestarium; else DIR="${HOME:?HOME is not set}/requestarium"; fi
  fi
  case "$DIR" in /*) ;; *) DIR="$(pwd)/$DIR" ;; esac
  DIR="${DIR%/}"
  case "$DIR" in "" | / | /bin | /boot | /dev | /etc | /home | /lib | /opt | /proc | /root | /sbin | /sys | /tmp | /usr | /usr/* | /var) die "refusing to use $DIR as the install directory" ;; esac
  [ "$DIR" != "${HOME:-}" ] || die "refusing to use your home directory itself; pick a subdirectory with --dir"

  [ "$DRY_RUN" = false ] || say "dry run: nothing on this machine is changed"

  if [ "$ACTION" = uninstall ]; then
    uninstall
  else
    install_or_upgrade
  fi
}

usage() {
  sed -n '2,27p' "$SELF" 2>/dev/null | sed 's/^# \{0,1\}//' || true
  [ -r "$SELF" ] || echo "Usage: curl -fsSL https://get.requestarium.com | sh -s -- [--domain <name>] [--port <port>] [--dir <path>] [--version <x.y.z>] [--admin-email <email>] [--yes] [--dry-run] [--uninstall [--purge]]"
}

need_value() { [ $# -ge 2 ] && [ -n "$2" ] || die "$1 needs a value"; }

# --- Output ---------------------------------------------------------------------------------------------------------

if [ -t 2 ] && [ -z "${NO_COLOR:-}" ]; then
  C_BOLD=$(printf '\033[1m'); C_RED=$(printf '\033[31m'); C_GREEN=$(printf '\033[32m'); C_YELLOW=$(printf '\033[33m'); C_RESET=$(printf '\033[0m')
else
  C_BOLD=""; C_RED=""; C_GREEN=""; C_YELLOW=""; C_RESET=""
fi

say() { printf '%s==>%s %s\n' "$C_BOLD" "$C_RESET" "$*" >&2; }
warn() { printf '%swarning:%s %s\n' "$C_YELLOW" "$C_RESET" "$*" >&2; }
die() { printf '%serror:%s %s\n' "$C_RED" "$C_RESET" "$*" >&2; exit 1; }

# run prints and runs a command, or only prints it in a dry run.
run() {
  if [ "$DRY_RUN" = true ]; then
    printf '   would run: %s\n' "$*" >&2
    return 0
  fi
  "$@"
}

# in_dir runs a command inside the install directory (Compose reads compose.yaml and .env from there).
in_dir() {
  if [ "$DRY_RUN" = true ]; then
    printf '   would run in %s: %s\n' "$DIR" "$*" >&2
    return 0
  fi
  (cd "$DIR" && "$@")
}

# confirm asks a yes/no question on the terminal, also when the script itself comes from a pipe.
confirm() {
  [ "$ASSUME_YES" = false ] || return 0
  [ "$DRY_RUN" = false ] || { printf '   would ask: %s\n' "$1" >&2; return 0; }
  if ! (: </dev/tty) 2>/dev/null; then
    die "$1 There is no terminal to ask: run again with --yes"
  fi
  printf '%s [y/N] ' "$1" >/dev/tty
  read -r answer </dev/tty || answer=""
  case "$answer" in y | Y | yes | YES | Yes) return 0 ;; *) return 1 ;; esac
}

# --- Checks ---------------------------------------------------------------------------------------------------------

check_platform() {
  os=$(uname -s)
  arch=$(uname -m)
  case "$os" in
    Linux)
      if grep -qi microsoft /proc/version 2>/dev/null; then platform="Linux (WSL)"; else platform=Linux; fi ;;
    Darwin) platform=macOS ;;
    MINGW* | MSYS* | CYGWIN*) die "run this inside WSL on Windows (https://learn.microsoft.com/windows/wsl/install), with Docker Desktop's WSL integration on" ;;
    *) die "unsupported OS $os: Requestarium self-hosted runs on Linux, macOS or Windows with WSL" ;;
  esac
  case "$arch" in
    x86_64 | amd64) arch=amd64 ;;
    aarch64 | arm64) arch=arm64 ;;
    *) die "unsupported CPU $arch: the images are built for amd64 and arm64" ;;
  esac
  say "platform: $platform, $arch"
}

check_tools() {
  for tool in tar sed grep awk mktemp; do
    command -v "$tool" >/dev/null 2>&1 || die "$tool is required"
  done
  if command -v curl >/dev/null 2>&1; then
    FETCH=curl
  elif command -v wget >/dev/null 2>&1; then
    FETCH=wget
  else
    die "curl or wget is required"
  fi
  if command -v sha256sum >/dev/null 2>&1; then
    SHA256="sha256sum"
  elif command -v shasum >/dev/null 2>&1; then
    SHA256="shasum -a 256"
  else
    die "sha256sum or shasum is required to check the download"
  fi
}

check_docker() {
  if ! command -v docker >/dev/null 2>&1; then
    case "$platform" in
      macOS) die "Docker is required: install Docker Desktop (https://docs.docker.com/desktop/setup/install/mac-install/) or OrbStack, start it, and run this again" ;;
      "Linux (WSL)") die "Docker is required: install Docker Desktop for Windows and turn on WSL integration for this distribution (https://docs.docker.com/desktop/features/wsl/)" ;;
      *) die "Docker is required: install Docker Engine (https://docs.docker.com/engine/install/, or: curl -fsSL https://get.docker.com | sh) and run this again" ;;
    esac
  fi
  if ! docker compose version >/dev/null 2>&1; then
    die "Docker Compose v2 is required (the \`docker compose\` plugin): https://docs.docker.com/compose/install/"
  fi
  if ! err=$(docker info 2>&1 >/dev/null); then
    case "$err" in
      *"permission denied"*) die "your user cannot use Docker: run with sudo (curl ... | sudo sh) or add yourself to the docker group (sudo usermod -aG docker \$USER, then log in again)" ;;
      *) die "Docker is installed but not running: start Docker and run this again" ;;
    esac
  fi
  compose_version=$(docker compose version --short 2>/dev/null | sed 's/^v//')
  major=$(printf '%s' "$compose_version" | cut -d. -f1)
  minor=$(printf '%s' "$compose_version" | cut -d. -f2)
  if [ -n "$major" ] && [ "$major" -eq 2 ] 2>/dev/null && [ "${minor:-0}" -lt 20 ] 2>/dev/null; then
    die "Docker Compose $compose_version is too old: 2.20 or newer is needed"
  fi
  say "docker: $(docker version --format '{{.Server.Version}}' 2>/dev/null || echo '?'), compose $compose_version"
}

# port_busy succeeds when something on this machine already listens on TCP port $1 (best effort: unknown = free).
port_busy() {
  if command -v ss >/dev/null 2>&1; then
    ss -ltnH 2>/dev/null | awk '{print $4}' | grep -Eq "[:.]$1\$"
  elif command -v lsof >/dev/null 2>&1; then
    lsof -nP -iTCP:"$1" -sTCP:LISTEN >/dev/null 2>&1
  elif command -v netstat >/dev/null 2>&1; then
    netstat -an 2>/dev/null | grep -i listen | awk '{print $4}' | grep -Eq "[:.]$1\$"
  else
    return 1
  fi
}

check_ports() {
  if [ -n "$DOMAIN" ]; then
    for p in 80 443; do
      ! port_busy "$p" || die "port $p is already in use: Requestarium's web server needs ports 80 and 443 for $DOMAIN"
    done
  else
    ! port_busy "$PORT" || die "port $PORT is already in use: pick another with --port"
  fi
}

# --- Downloads ------------------------------------------------------------------------------------------------------

fetch() {
  if [ "$FETCH" = curl ]; then
    curl -fsSL --proto '=https,file' --retry 3 -o "$2" "$1"
  else
    wget -q -O "$2" "$1"
  fi
}

resolve_version() {
  if [ -n "$VERSION" ]; then
    return
  fi
  fetch "$DOWNLOADS/latest.json" "$WORK/latest.json" ||
    die "could not read $DOWNLOADS/latest.json: check your internet connection, or no self-hosted release is published yet (status: https://status.requestarium.com)"
  VERSION=$(tr -d '\n' <"$WORK/latest.json" | sed -n 's/.*"version"[[:space:]]*:[[:space:]]*"\([0-9][0-9.]*\)".*/\1/p')
  printf '%s' "$VERSION" | grep -Eq '^[0-9]+\.[0-9]+\.[0-9]+$' || die "could not read the latest version from $DOWNLOADS/latest.json"
}

# download_bundle fetches the Compose bundle of $VERSION, checks it against the release's checksums.txt and unpacks
# it into $WORK/bundle.
download_bundle() {
  name="requestarium-compose-$VERSION"
  say "downloading Requestarium $VERSION"
  fetch "$DOWNLOADS/$VERSION/checksums.txt" "$WORK/checksums.txt" || die "release $VERSION not found at $DOWNLOADS/$VERSION/"
  fetch "$DOWNLOADS/$VERSION/$name.tar.gz" "$WORK/$name.tar.gz" || die "could not download $name.tar.gz"
  expected=$(awk -v f="$name.tar.gz" '$2 == f || $2 == "*" f {print $1}' "$WORK/checksums.txt")
  [ -n "$expected" ] || die "checksums.txt of $VERSION does not list $name.tar.gz"
  actual=$(cd "$WORK" && $SHA256 "$name.tar.gz" | awk '{print $1}')
  [ "$expected" = "$actual" ] || die "checksum mismatch for $name.tar.gz: the download is corrupt or was tampered with"
  say "checksum ok"
  mkdir "$WORK/bundle"
  tar -xzf "$WORK/$name.tar.gz" -C "$WORK/bundle"
  BUNDLE="$WORK/bundle/$name"
  for file in compose.yaml .env.example install.sh upgrade.sh Caddyfile; do
    [ -f "$BUNDLE/$file" ] || die "the bundle has no $file"
  done
}

# --- .env -----------------------------------------------------------------------------------------------------------

# env_get prints the value of $1 in $2 (default: the install's .env).
env_get() { sed -n "s/^$1=//p" "${2:-$DIR/.env}" | tail -n 1; }

# env_set sets $1=$2 in the .env file $3, replacing the line or appending it. No sed -i (GNU and BSD differ), and the
# value never reaches a command line or the output.
env_set() {
  file=$3
  tmp="$file.tmp.$$"
  awk -v k="$1" -v v="$2" 'BEGIN { done = 0 }
    $0 ~ "^#? ?" k "=" && !done { print k "=" v; done = 1; next }
    { print }
    END { if (!done) print k "=" v }' "$file" >"$tmp"
  cat "$tmp" >"$file"
  rm -f "$tmp"
}

# configure_env writes the choices of this run into a new .env in the bundle (secrets come from install.sh).
configure_env() {
  env="$BUNDLE/.env"
  cp "$BUNDLE/.env.example" "$env"
  chmod 600 "$env"
  env_set REQUESTARIUM_VERSION "$VERSION" "$env"
  if [ -n "$DOMAIN" ]; then
    env_set REQUESTARIUM_DOMAIN "$DOMAIN" "$env"
    PUBLIC_URL="https://$DOMAIN"
  else
    # Local trial: plain HTTP on localhost only. Caddy listens on :80 in the container, published on 127.0.0.1.
    env_set REQUESTARIUM_DOMAIN localhost "$env"
    env_set REQUESTARIUM_SITE_ADDRESS ":80" "$env"
    env_set REQUESTARIUM_HTTP_PORT "127.0.0.1:$PORT" "$env"
    # Caddy also publishes 443: a random free port on loopback ("127.0.0.1::443"), unused in the trial.
    env_set REQUESTARIUM_HTTPS_PORT "127.0.0.1:" "$env"
    PUBLIC_URL="http://localhost:$PORT"
    env_set REQUESTARIUM_PUBLIC_URL "$PUBLIC_URL" "$env"
  fi
  [ -z "$ADMIN_EMAILS" ] || env_set TAIRI_ADMIN_EMAILS "$ADMIN_EMAILS" "$env"
  # Sign-up codes go to the backend log until mail is set up in Settings > Installation > Email.
}

# --- Install / upgrade ----------------------------------------------------------------------------------------------

install_or_upgrade() {
  check_platform
  check_tools
  check_docker

  WORK=$(mktemp -d 2>/dev/null || mktemp -d -t requestarium)
  trap 'rm -rf "$WORK"' EXIT
  trap 'exit 130' INT TERM

  if [ -f "$DIR/.env" ] && [ -f "$DIR/compose.yaml" ]; then
    upgrade
    return
  fi
  if [ -d "$DIR" ] && [ -n "$(ls -A "$DIR" 2>/dev/null)" ]; then
    die "$DIR exists and is not a Requestarium install: pick another directory with --dir"
  fi

  check_ports
  resolve_version
  download_bundle
  configure_env

  say "installing into $DIR"
  run mkdir -p "$DIR"
  run cp -R "$BUNDLE/." "$DIR/"
  run chmod 600 "$DIR/.env"
  # install.sh fills every empty secret (database password, JWT, MFA and data encryption keys) with random values
  # generated on this machine; it prints only their names.
  in_dir ./install.sh >/dev/null
  say "generated the database password and encryption keys in $DIR/.env (keep a copy of that file somewhere safe)"

  say "pulling images (a few hundred MB the first time)"
  in_dir docker compose pull --quiet
  say "starting Requestarium"
  in_dir docker compose up -d --remove-orphans
  wait_ready
  print_done
}

upgrade() {
  current=$(env_get REQUESTARIUM_VERSION)
  resolve_version
  [ -z "$DOMAIN" ] || [ "$DOMAIN" = "$(env_get REQUESTARIUM_DOMAIN)" ] || warn "--domain is ignored on an existing install: change REQUESTARIUM_DOMAIN in $DIR/.env"
  if [ -n "$(env_get REQUESTARIUM_PUBLIC_URL)" ]; then
    PUBLIC_URL=$(env_get REQUESTARIUM_PUBLIC_URL)
  else
    PUBLIC_URL="https://$(env_get REQUESTARIUM_DOMAIN)"
  fi

  if [ "$current" = "$VERSION" ]; then
    say "Requestarium $VERSION is already installed in $DIR; making sure it is running"
    in_dir docker compose up -d --remove-orphans
    wait_ready
    print_done
    return
  fi

  if [ "$current" = latest ] || [ -z "$current" ]; then
    die "$DIR runs an unpinned version (REQUESTARIUM_VERSION=${current:-empty}): upgrade it with $DIR/upgrade.sh <version>"
  fi
  if version_lt "$VERSION" "$current"; then
    die "$DIR runs $current, newer than $VERSION: going back needs the pre-upgrade backup ($DIR/upgrade.sh --rollback)"
  fi

  confirm "Upgrade Requestarium in $DIR from $current to $VERSION? A database backup is taken first." || die "cancelled"
  download_bundle

  say "updating the release files in $DIR (.env and certs/ are kept)"
  for file in compose.yaml Caddyfile install.sh backup.sh upgrade.sh README.md .env.example; do
    [ ! -f "$BUNDLE/$file" ] || run cp "$BUNDLE/$file" "$DIR/$file"
  done
  [ ! -d "$BUNDLE/monitoring" ] || run cp -R "$BUNDLE/monitoring/." "$DIR/monitoring/"
  # New releases may add secrets; install.sh fills only the empty ones and never replaces a value.
  in_dir ./install.sh >/dev/null
  # upgrade.sh pulls, checks the migrations against the database, takes a backup and restarts on the new version.
  in_dir ./upgrade.sh "$VERSION"
  wait_ready
  print_done
}

# version_lt succeeds when version $1 is older than $2.
version_lt() {
  [ "$1" != "$2" ] && [ "$(printf '%s\n%s\n' "$1" "$2" | sort -t. -k1,1n -k2,2n -k3,3n | head -n 1)" = "$1" ]
}

# wait_ready polls the backend's /ready through the web server until it answers (migrations run on first start).
wait_ready() {
  [ "$DRY_RUN" = false ] || { printf '   would wait for %s/api/ready\n' "$PUBLIC_URL" >&2; return 0; }
  if [ -n "$DOMAIN" ] || [ -z "$(env_get REQUESTARIUM_PUBLIC_URL)" ]; then
    host=$(env_get REQUESTARIUM_DOMAIN)
    port=$(env_get REQUESTARIUM_HTTPS_PORT); port=${port:-443}; port=${port##*:}
    # The certificate may not be issued yet (DNS still pointing elsewhere), so this check does not verify it.
    url="https://$host:$port/api/ready"
    probe() { curl -fsk --max-time 5 --resolve "$host:$port:127.0.0.1" -o /dev/null "$url" 2>/dev/null; }
  else
    url="$(env_get REQUESTARIUM_PUBLIC_URL)/api/ready"
    url=$(printf '%s' "$url" | sed 's#//localhost#//127.0.0.1#')
    probe() {
      if command -v curl >/dev/null 2>&1; then
        curl -fs --max-time 5 -o /dev/null "$url" 2>/dev/null
      else
        wget -q -T 5 -O /dev/null "$url" 2>/dev/null
      fi
    }
  fi
  say "waiting for Requestarium to answer (database migrations run on the first start)"
  i=0
  while [ $i -lt 90 ]; do
    if probe; then
      say "ready"
      return 0
    fi
    i=$((i + 1))
    sleep 2
  done
  warn "Requestarium did not answer within 3 minutes. See: cd $DIR && docker compose ps && docker compose logs backend"
  return 1
}

print_done() {
  [ "$DRY_RUN" = false ] || return 0
  printf '\n%sRequestarium is running:%s %s\n\n' "$C_GREEN" "$C_RESET" "$PUBLIC_URL" >&2
  cat >&2 <<EOF
Next steps:
  1. Open $PUBLIC_URL and sign up. $(if [ -n "$ADMIN_EMAILS" ]; then echo "Installation administrators: $ADMIN_EMAILS."; else echo "The first account becomes the installation administrator."; fi)
  2. Until email is set up, the sign-up code is in the backend log:
       cd $DIR && docker compose logs backend | grep "log mail provider"
     Set up SMTP in Settings > Installation > Email.
  3. Without a licence Requestarium runs on the Free plan. To add one, set TAIRI_LICENSE_PROVIDER=manual
     in $DIR/.env, run docker compose up -d, and paste the licence in Settings > License.
  4. Keep a copy of $DIR/.env outside this machine: it holds the encryption keys your data needs.

Manage it from $DIR:
  docker compose ps | logs -f backend | stop | start
  ./upgrade.sh <version>        or run this installer again to move to the latest release
  ./upgrade.sh --rollback       go back to the version before the last upgrade
  Uninstall: curl -fsSL https://get.requestarium.com | sh -s -- --uninstall --dir $DIR
EOF
  if [ -z "$DOMAIN" ] && [ -n "$(env_get REQUESTARIUM_PUBLIC_URL)" ]; then
    printf '\nThis is a local trial (http, this machine only). For your team, install on a server with --domain.\n' >&2
  fi
}

# --- Uninstall ------------------------------------------------------------------------------------------------------

uninstall() {
  [ -f "$DIR/compose.yaml" ] || die "no Requestarium install in $DIR (pass --dir)"
  command -v docker >/dev/null 2>&1 || die "docker is required to stop the containers"
  if [ "$PURGE" = true ]; then
    confirm "Delete Requestarium in $DIR with its database, backups and keys? This cannot be undone." || die "cancelled"
    in_dir docker compose --profile db --profile monitoring down --volumes --remove-orphans
    run rm -rf "$DIR"
    say "removed Requestarium, its data and $DIR"
  else
    confirm "Stop and remove the Requestarium containers in $DIR? The database and $DIR stay." || die "cancelled"
    in_dir docker compose --profile db --profile monitoring down --remove-orphans
    say "removed the containers. Data volumes and $DIR are kept: run the installer again to start it, or --uninstall --purge to delete everything"
  fi
}

SELF=$0
main "$@"
