#!/usr/bin/env bash
# Day-to-day management of a VitalRix on-premises server.
#
#   ./vitalrix status                  containers and the health of every service (exit code 1 when something is down)
#   ./vitalrix logs [component]        follow the logs (vitalrix, postgres, redis, proxy)
#   ./vitalrix start | stop | restart  (start and restart also apply changes to .env)
#   ./vitalrix upgrade <version>       online: download that release from VitalRix, back up, then move to it
#   ./vitalrix upgrade <bundle.tar.gz> offline: the same from a downloaded bundle (vitalrix-onprem-<version>-<arch>.tar.gz)
#   ./vitalrix backup                  database and stored files into backups/<time>/
#   ./vitalrix restore <backup dir>    put a backup back (stops VitalRix while it runs)
#   ./vitalrix license <file>          install a new license file
#   ./vitalrix support-bundle          a file for VitalRix support (secrets removed)
#   ./vitalrix ca-cert                 the certificate authority to trust when VITALRIX_TLS=internal
#   ./vitalrix create-admin --email … [--org …]   first administrator (password from VITALRIX_ADMIN_PASSWORD, or asked)
#   ./vitalrix push-images <registry>  copy the bundle's images to your registry (Kubernetes without internet access)
set -euo pipefail
cd "$(dirname "$0")"
DEFAULT_DOWNLOADS=https://downloads.vitalrix.com
# releases up to 1.0.0 named an image registry that never went live; installations still pointing at it move to this one
RETIRED_IMAGE=registry.vitalrix.com/vitalrix
DEFAULT_IMAGE=downloads.vitalrix.com/vitalrix

dc() { docker compose "$@"; }
envval() { grep -E "^$1=" .env 2>/dev/null | tail -1 | cut -d= -f2-; }
setenv() { if grep -qE "^$1=" .env; then sed -i.bak "s|^$1=.*|$1=$2|" .env && rm -f .env.bak; else echo "$1=$2" >> .env; fi; }
stamp() { date -u +%Y%m%dT%H%M%SZ; }
need_env() { [ -f .env ] || { echo "vitalrix: run ./install.sh first" >&2; exit 1; }; }

# The website CMS is no longer part of on premises: remove the proxy site older versions put in place. Prints "changed" when it does.
sync_website() {
  mkdir -p sites
  [ -f sites/website.caddy ] && { rm -f sites/website.caddy; echo changed; }
  return 0
}

image_ref() { echo "$(envval VITALRIX_IMAGE):$(envval VITALRIX_VERSION)"; }

# Waits until every component answers; prints the status table. Returns 1 after $1 seconds.
wait_healthy() {
  local until=$(( $(date +%s) + ${1:-600} ))
  while [ "$(date +%s)" -lt "$until" ]; do
    if dc exec -T vitalrix vitalrix status >/dev/null 2>&1; then return 0; fi
    sleep 5
  done
  dc exec -T vitalrix vitalrix status || true
  return 1
}

backup() {
  local dir="backups/$(stamp)"; mkdir -p "$dir"; chmod 700 backups "$dir"
  echo "Backing up the database…"
  dc exec -T postgres pg_dump -U vitalrix -d vitalrix -Fc > "$dir/database.dump"
  echo "Backing up stored files (media, session replays)…"
  dc exec -T vitalrix tar -C /data -czf - . > "$dir/data.tar.gz"
  cp .env "$dir/env" && chmod 600 "$dir/env"
  [ -f license/vitalrix.license ] && cp license/vitalrix.license "$dir/"
  envval VITALRIX_VERSION > "$dir/VERSION"
  echo "Backup written to $dir ($(du -sh "$dir" | cut -f1)). It contains secrets: keep it as safe as the server."
  LAST_BACKUP="$dir"
}

# The bundle files that belong to a release (never .env, license/, certs/, backups/). Each is replaced by a rename, so
# this script, which bash is still reading, keeps running from its old copy.
MANAGED="docker-compose.yml Caddyfile .env.example install.sh vitalrix README.md VERSION IMAGE"
refresh_files() {
  local src="$1" f
  for f in $MANAGED; do [ -f "$src/$f" ] && { cp -p "$src/$f" "$f.new" && mv -f "$f.new" "$f"; }; done
  if [ -d "$src/helm" ]; then rm -rf helm.new && cp -R "$src/helm" helm.new && rm -rf helm && mv helm.new helm; fi
  mkdir -p sites
  # settings a newer release added get their default value
  while IFS= read -r line; do
    case "$line" in ''|\#*) continue ;; esac
    grep -qE "^${line%%=*}=" .env || echo "$line" >> .env
  done < .env.example
}

upgrade() {
  local target="${1:?usage: ./vitalrix upgrade <version> (online) or ./vitalrix upgrade <bundle.tar.gz> (offline)}"
  local from to src image
  from=$(envval VITALRIX_VERSION)
  WORK=$(mktemp -d); trap 'rm -rf "$WORK"' EXIT  # global: the trap runs after this function returns
  local work="$WORK"
  if [ -f "$target" ]; then
    echo "Reading the bundle $target…"
    tar -C "$work" -xzf "$target" 2>/dev/null || { echo "upgrade: $target is not a VitalRix on-premises bundle (it does not unpack)" >&2; exit 1; }
    src=$(find "$work" -mindepth 1 -maxdepth 1 -type d -name 'vitalrix-onprem-*' | head -1)
    [ -n "$src" ] && [ -f "$src/VERSION" ] || { echo "upgrade: $target is not a VitalRix on-premises bundle" >&2; exit 1; }
    if [ -f "$src/ARCH" ]; then
      local host; case "$(docker info --format '{{.Architecture}}' 2>/dev/null)" in x86_64|amd64) host=amd64 ;; aarch64|arm64) host=arm64 ;; *) host="" ;; esac
      [ -z "$host" ] || [ "$host" = "$(cat "$src/ARCH")" ] || { echo "upgrade: that bundle is for $(cat "$src/ARCH") servers, this one is $host" >&2; exit 1; }
    fi
  else
    local base name; base=$(envval VITALRIX_DOWNLOADS_URL); base="${base:-$DEFAULT_DOWNLOADS}"; base="${base%/}"
    name="vitalrix-onprem-$target.tar.gz"
    echo "Downloading VitalRix $target from $base…"
    curl -fsSL "$base/onprem/$target/$name" -o "$work/$name" && curl -fsSL "$base/onprem/$target/$name.sha256" -o "$work/$name.sha256" \
      || { echo "upgrade: could not download release $target from $base. Check the version, or upgrade offline from a bundle: ./vitalrix upgrade <bundle.tar.gz>" >&2; exit 1; }
    [ "$(cut -d' ' -f1 "$work/$name.sha256")" = "$( (sha256sum "$work/$name" 2>/dev/null || shasum -a 256 "$work/$name") | cut -d' ' -f1)" ] \
      || { echo "upgrade: the download does not match its checksum; nothing was changed" >&2; exit 1; }
    tar -C "$work" -xzf "$work/$name" || { echo "upgrade: the download does not unpack; nothing was changed" >&2; exit 1; }
    src="$work/vitalrix-onprem-$target"
  fi
  to=$(cat "$src/VERSION")
  image=$(envval VITALRIX_IMAGE)
  { [ -z "$image" ] || [ "$image" = "$RETIRED_IMAGE" ]; } && image=$(cat "$src/IMAGE" 2>/dev/null || echo "$DEFAULT_IMAGE")

  # the new image must be on this server before anything changes, so a failed download leaves the installation as it was
  if [ -d "$src/images" ]; then
    echo "Loading the images…"
    for t in "$src"/images/*.tar; do docker load -q -i "$t"; done
  elif ! docker image inspect "$image:$to" >/dev/null 2>&1; then
    echo "Pulling $image:$to…"
    docker pull -q "$image:$to" || { echo "upgrade: could not pull $image:$to; nothing was changed" >&2; exit 1; }
  fi
  docker image inspect "$image:$to" >/dev/null 2>&1 || { echo "upgrade: $image:$to is not available; nothing was changed" >&2; exit 1; }

  echo "Upgrading $from -> $to. A backup is taken first."
  backup
  cp .env "$work/env.before"
  refresh_files "$src"
  setenv VITALRIX_IMAGE "$image"
  setenv VITALRIX_VERSION "$to"
  sync_website >/dev/null
  docker image inspect postgres:16-alpine redis:7-alpine caddy:2-alpine >/dev/null 2>&1 || dc pull -q postgres redis proxy
  dc up -d
  echo "Waiting for VitalRix (database migrations run on start)…"
  if wait_healthy 900; then echo "Upgraded to $to."; return 0; fi
  echo "VitalRix $to is not healthy yet (./vitalrix logs). To go back to $from:" >&2
  echo "  set VITALRIX_VERSION=$from in .env, then ./vitalrix restore $LAST_BACKUP" >&2
  exit 1
}

push_images() {
  local registry="${1:?usage: ./vitalrix push-images <registry>, for example registry.acme.internal}" t name version
  registry="${registry%/}"
  ls images/*.tar >/dev/null 2>&1 || { echo "push-images: run it in the unpacked offline bundle (it needs images/)" >&2; exit 1; }
  version=$(cat VERSION); name=$(cat IMAGE 2>/dev/null || echo "$DEFAULT_IMAGE")
  echo "Loading the bundle's images into this machine's Docker (this replaces its postgres:16-alpine, redis:7-alpine and"
  echo "caddy:2-alpine tags with the bundle's: run it on a workstation or transfer host, not on a server running other containers)."
  for t in images/*.tar; do docker load -q -i "$t"; done
  for ref in "$name:$version" postgres:16-alpine redis:7-alpine caddy:2-alpine; do
    local short="${ref##*/}"
    docker tag "$ref" "$registry/$short" && docker push -q "$registry/$short"
    echo "pushed $registry/$short"
  done
  echo "Helm: image.repository=$registry/vitalrix (bundled database: bundled.postgresImage=$registry/postgres:16-alpine, bundled.redisImage=$registry/redis:7-alpine)."
}

cmd="${1:-status}"
case "$cmd" in push-images|help|-h|--help) ;; *) need_env ;; esac
case "$cmd" in
  status) dc ps; echo; dc exec -T vitalrix vitalrix status ;;
  logs) dc logs -f --tail 200 "${2:-vitalrix}" ;;
  start) sync_website >/dev/null; dc up -d ;;
  stop) dc stop ;;
  restart)
    changed=$(sync_website)
    dc up -d
    dc up -d --force-recreate vitalrix
    [ -n "$changed" ] && dc up -d --force-recreate proxy
    echo "Restarted. VitalRix is ready in a minute or two: ./vitalrix status" ;;
  backup) backup ;;
  restore)
    dir="${2:?usage: ./vitalrix restore backups/<time>}"
    [ -f "$dir/database.dump" ] || { echo "no database.dump in $dir" >&2; exit 1; }
    read -r -p "This replaces all current data with the backup from $dir. Type RESTORE to continue: " ok; [ "$ok" = RESTORE ] || exit 1
    dc stop vitalrix
    dc exec -T postgres pg_restore -U vitalrix -d vitalrix --clean --if-exists --no-owner < "$dir/database.dump"
    dc run --rm -T --entrypoint sh vitalrix -c 'rm -rf /data/* && tar -C /data -xzf -' < "$dir/data.tar.gz"
    dc up -d vitalrix
    echo "Restored from $dir." ;;
  upgrade) upgrade "${2:-}" ;;
  license)
    f="${2:?usage: ./vitalrix license <file>}"; cp "$f" license/vitalrix.license && chmod 644 license/vitalrix.license
    echo "License file installed. It applies within 30 seconds (VitalRix uses the better of this file and a license installed in Settings > Billing)." ;;
  support-bundle)
    out="vitalrix-support-$(stamp).tar.gz"; tmp=$(mktemp -d)
    { envval VITALRIX_VERSION; docker version --format '{{.Server.Version}}'; docker compose version; uname -a; } > "$tmp/versions.txt" 2>&1 || true
    dc ps > "$tmp/containers.txt" 2>&1 || true
    dc exec -T vitalrix vitalrix status > "$tmp/health.txt" 2>&1 || true
    for c in vitalrix postgres redis proxy; do dc logs --no-color --tail 5000 "$c" > "$tmp/logs-$c.txt" 2>&1 || true; done
    # settings without any secret value
    sed -E 's/^((POSTGRES_PASSWORD|JWT_ACCESS_SECRET|INTERNAL_SECRET|INTEGRATION_ENCRYPTION_KEY|REVALIDATE_SECRET|PREVIEW_SECRET|METRICS_TOKEN|ONCALL_LINK_SECRET|SMTP_PASSWORD|GOOGLE_CLIENT_SECRET|ANTHROPIC_API_KEY)=).+/\1<redacted>/' .env > "$tmp/env.txt"
    df -h > "$tmp/disk.txt" 2>&1 || true; free -m > "$tmp/memory.txt" 2>&1 || true
    tar -C "$tmp" -czf "$out" . && rm -rf "$tmp"
    echo "Wrote $out. Send it to VitalRix support with a description of the problem." ;;
  ca-cert) dc exec -T proxy cat /data/caddy/pki/authorities/local/root.crt > vitalrix-ca.crt && echo "Wrote vitalrix-ca.crt: add it to your computers' trusted certificate authorities." ;;
  create-admin)
    shift
    if [ -z "${VITALRIX_ADMIN_PASSWORD:-}" ] && [[ " $* " != *" --password "* ]]; then
      read -r -s -p "Administrator password (12+ characters): " VITALRIX_ADMIN_PASSWORD; echo
    fi
    export VITALRIX_ADMIN_PASSWORD
    dc exec -T -e VITALRIX_ADMIN_PASSWORD vitalrix vitalrix create-admin "$@" ;;
  push-images) push_images "${2:-}" ;;
  *) sed -n '2,16p' "$0"; exit 1 ;;
esac
