#!/bin/sh
# Tazmu server updater. install.sh puts it in your install folder; run it there:
#   sh update.sh            # update to the latest release
#   sh update.sh 0.1.107    # move to a specific release, 0.1.106 or later
#
# What it does:
#   1. Pulls the new image from registry.tazmu.xyz. If the registry login
#      expired (server credentials last 90 days), it asks for a new one.
#   2. Backs up the data volume to backups/ with the server's backup tool.
#   3. Writes the new version into .env and recreates the containers.
#      The data volume is kept; only the containers are replaced.
#   4. Waits for the new server to report healthy, then prints its license
#      status.
#
# Moving to an older release is not an undo. `sh update.sh <old version>` only
# switches the image: the old build then runs on data the newer one already
# changed, and nothing checks that it can read it. It asks before it does that.
# To really roll back, switch the version, then restore the backup update.sh
# made before the upgrade (backups/tazmu-<old version>-<time>.tgz). The steps
# are at https://tazmu.xyz/install#roll-back
#
# Settings, all optional:
#   TAZMU_CREDENTIAL  a new server credential, if the registry login expired
#   TAZMU_FORCE=1     reinstall the running version, and move to an older
#                     release without asking
set -eu

REGISTRY=registry.tazmu.xyz
IMAGE=$REGISTRY/tazmu/server
RELEASES=https://accounts.tazmu.xyz/v1/releases/server
ROLLBACK_DOCS=https://tazmu.xyz/install#roll-back
# Older images do not put the engine CLIs in /data/.npm-global/bin on PATH.
MIN_VERSION=0.1.106

say() { printf '%s\n' "$*"; }
die() { printf 'tazmu: %s\n' "$*" >&2; exit 1; }
# True when there is a terminal to ask on (/dev/tty can exist without one).
have_tty() { (: </dev/tty) 2>/dev/null; }

# True when version $1 sorts before version $2 (numeric, dot by dot).
version_lt() {
  awk -v a="$1" -v b="$2" 'BEGIN {
    n = split(a, x, "."); m = split(b, y, "."); if (m > n) n = m
    for (i = 1; i <= n; i++) { if (x[i] + 0 < y[i] + 0) exit 0; if (x[i] + 0 > y[i] + 0) exit 1 }
    exit 1
  }'
}

check_version() {
  case $1 in
    [0-9]*.[0-9]*.[0-9]*) ;;
    *) die "'$1' is not a Tazmu version such as $MIN_VERSION." ;;
  esac
  case $1 in
    *[!0-9A-Za-z.+-]*) die "'$1' is not a Tazmu version such as $MIN_VERSION." ;;
  esac
  if version_lt "$1" "$MIN_VERSION"; then
    die "Tazmu $1 is too old for this updater: its engines are not on PATH, so no bot can run. Use $MIN_VERSION or later."
  fi
}

# Prints the server's license status, read over loopback inside the container.
# Releases without licensing answer 404, and then this prints nothing.
license_status() {
  docker compose exec -T omb node - 2>/dev/null <<'EOF' || true
const port = process.env.OMB_PORT || 8799;
fetch(`http://127.0.0.1:${port}/api/license`, { signal: AbortSignal.timeout(5000) })
  .then(async (res) => {
    if (!res.ok) return;
    const view = await res.json();
    if (!view || typeof view.message !== "string") return;
    const lines = ["", `License: ${view.message}`];
    if (view.grace && typeof view.grace.daysRemaining === "number") {
      lines.push(`Bots keep working for ${view.grace.daysRemaining} more day(s).`);
    }
    if (view.locked) lines.push("New bot turns are refused until this is fixed. Bots, chats and settings are kept.");
    const signIn = view.mode !== "off" &&
      (view.reason === "signed_out" || view.reason === "unauthorized" || (!view.account && (view.locked || view.grace)));
    if (signIn) {
      lines.push(view.message.includes("tazmu license login")
        ? "From this folder, `tazmu license login` is:"
        : "Sign in under Settings > License in the web or desktop app, or from this folder run:");
      lines.push("  docker compose exec omb node dist-server/tazmu.js license login --email you@example.com");
    } else if (view.locked && view.manageUrl) {
      lines.push(`Manage your subscription at ${view.manageUrl}`);
    }
    console.log(lines.join("\n"));
  })
  .catch(() => {});
EOF
}

cd "$(dirname "$0")"
[ -f compose.yaml ] && [ -f .env ] || die "run this in the folder install.sh created."
# Compose prefers variables from the environment over .env, so a leftover
# `export TAZMU_VERSION=...` would keep the old version. .env decides.
unset COMPOSE_PROJECT_NAME TAZMU_VERSION TAZMU_HTTP TAZMU_HTTPS TAZMU_SITE_ADDRESS TAZMU_PUBLIC_URL TAZMU_PUBLIC_HOST
CURRENT=$(sed -n 's/^TAZMU_VERSION=//p' .env)
TARGET=${1:-$(curl -fsS "$RELEASES" | sed -n 's/.*"latest":"\([0-9][0-9.]*\)".*/\1/p')}
[ -n "$TARGET" ] || die "could not read the latest version from $RELEASES."
check_version "$TARGET"
if [ "$TARGET" = "$CURRENT" ] && [ "${TAZMU_FORCE:-}" != 1 ]; then
  say "Tazmu $CURRENT is already the latest release."
  exit 0
fi

# Going back: warn, point at the backup taken before the upgrade, and ask.
DOWNGRADE=
RESTORE=
if [ -n "$CURRENT" ] && version_lt "$TARGET" "$CURRENT"; then
  DOWNGRADE=1
  RESTORE=$(find backups -maxdepth 1 -name "tazmu-$TARGET-*.tgz" 2>/dev/null | sort | tail -n 1)
  say "Tazmu $TARGET is older than the running $CURRENT."
  say "Switching back only changes the image. $TARGET would run on data that $CURRENT"
  say "already changed, and nothing checks that $TARGET can read it."
  if [ -n "$RESTORE" ]; then
    say "To roll back fully, restore the backup taken before the upgrade once this"
    say "finishes: $RESTORE"
  else
    say "No backup from $TARGET is in backups/, so there is nothing to restore."
  fi
  say "Restore steps: $ROLLBACK_DOCS"
  if [ "${TAZMU_FORCE:-}" != 1 ]; then
    have_tty || die "not switching without a terminal to ask on. Set TAZMU_FORCE=1 to switch anyway."
    printf 'Switch to %s anyway? [y/N] ' "$TARGET" >/dev/tty
    read -r answer </dev/tty || answer=
    case $answer in
      y | Y | yes | YES) ;;
      *) die "nothing was changed." ;;
    esac
  fi
fi
say "Updating Tazmu $CURRENT -> $TARGET"

# 1. Pull first, so a failed download leaves the running server alone.
# The server renews its own credential every few months, which ends the one
# Docker logged in with. Log in again with the server's current credential
# (server 0.1.110 and later) before asking for a new one.
pull_with_server_credential() {
  SERVER_CREDENTIAL=$(docker compose exec -T omb node dist-server/tazmu.js license credential 2>/dev/null) || return 1
  [ -n "$SERVER_CREDENTIAL" ] || return 1
  printf '%s' "$SERVER_CREDENTIAL" | docker login "$REGISTRY" -u tazmu --password-stdin >/dev/null 2>&1 || return 1
  docker pull -q "$IMAGE:$TARGET" >/dev/null 2>&1
}
if ! docker pull -q "$IMAGE:$TARGET" >/dev/null 2>&1 && ! pull_with_server_credential; then
  say "The registry refused the pull. Your login may have expired."
  if [ -z "${TAZMU_CREDENTIAL:-}" ]; then
    have_tty || die "set TAZMU_CREDENTIAL to a new server credential."
    say "Paste a new server credential from https://accounts.tazmu.xyz/billing (Servers)."
    printf 'Credential (hidden): ' >/dev/tty
    stty -echo </dev/tty
    read -r TAZMU_CREDENTIAL </dev/tty
    stty echo </dev/tty
    printf '\n' >/dev/tty
  fi
  printf '%s' "$TAZMU_CREDENTIAL" | docker login "$REGISTRY" -u tazmu --password-stdin >/dev/null \
    || die "registry.tazmu.xyz refused the credential."
  docker pull -q "$IMAGE:$TARGET" >/dev/null || die "could not pull $IMAGE:$TARGET."
fi

# 2. Backup. backup-data.mjs copies SQLite with its online backup API and
# checks every copy, so the server keeps running. Images older than 0.1.106
# do not have it; then stop the server and tar the volume instead. The engine
# CLIs (.npm-global) are left out: reinstall them with npm install -g.
mkdir -p backups
chmod 700 backups
ARCHIVE=backups/tazmu-$CURRENT-$(date -u +%Y%m%dT%H%M%SZ).tgz
say "Backing up the data volume to $ARCHIVE..."
if docker compose exec -T omb test -f /app/scripts/backup-data.mjs 2>/dev/null; then
  docker compose exec -T omb node /app/scripts/backup-data.mjs backup /data - \
    --exclude .npm --exclude .npm-global --exclude .cache >"$ARCHIVE" || { rm -f "$ARCHIVE"; die "backup failed; nothing was changed."; }
else
  docker compose stop omb caddy >/dev/null
  docker compose run --rm --no-deps -T omb tar czf - -C /data --exclude=./.npm --exclude=./.npm-global --exclude=./.cache . >"$ARCHIVE" \
    || { rm -f "$ARCHIVE"; docker compose up -d >/dev/null; die "backup failed; nothing was changed."; }
fi
chmod 600 "$ARCHIVE"

# 3. Switch the version and recreate the containers. The volume stays.
cp .env .env.previous
sed "s/^TAZMU_VERSION=.*/TAZMU_VERSION=$TARGET/" .env.previous >.env
docker compose up -d --quiet-pull

# 4. Wait for health.
tries=0
until [ "$(docker inspect -f '{{.State.Health.Status}}' "$(docker compose ps -q omb)")" = healthy ]; do
  tries=$((tries + 1))
  if [ "$tries" -gt 60 ]; then
    say "Tazmu $TARGET did not become healthy. Check: docker compose logs omb"
    say "Your data from before this update is in $ARCHIVE."
    die "to go back, run 'sh update.sh $CURRENT', then restore $ARCHIVE as $ROLLBACK_DOCS describes."
  fi
  sleep 3
done
say "Tazmu $TARGET is running. Backup: $ARCHIVE"
if [ -n "$DOWNGRADE" ]; then
  if [ -n "$RESTORE" ]; then
    say "It is running on the data $CURRENT left. Restore $RESTORE to finish the rollback: $ROLLBACK_DOCS"
  else
    say "It is running on the data $CURRENT left. $ARCHIVE holds that data if you move forward again."
  fi
fi
license_status
