#!/bin/bash
# Copyright 2026 ANNE Media - https://anne.media
# All rights reserved.
#
# Redistribution and use of this script, with or without modification, is
# permitted provided that the following conditions are met:
#
# 1. Redistributions of this script must retain the above copyright
#    notice, this list of conditions and the following disclaimer.
#
#  THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
#  WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
#  MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO
#  EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
#  SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
#  PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
#  OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
#  WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
#  OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
#  ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
# upgrade-annode.sh -- upgrade the annode application on a running AM·OS host.
#
# Usage:
#   upgrade-annode.sh                Upgrade the application only
#   upgrade-annode.sh restore PW     Also wipe annedb and restore from the
#                                    mirror snapshot. PW is the MariaDB root
#                                    password (from /root/mariadb_root_password.txt).
#
# Runs on the installed system as root. sysvinit, not systemd.

set -eu

RESTORESNAP="${1:-}"
DB_ROOT_USER_PASS="${2:-}"

ANNODE_USER="annode"
ANNODE_HOME="/home/$ANNODE_USER"
ANNODE_DIR="$ANNODE_HOME/annode"
ANNODE_DB="annedb"
ANNODE_SVC="/etc/rc.d/rc.annode"
MARIADB_SVC="/etc/rc.d/rc.mysqld"
ANNODE_LOG="/var/log/annode.log"
MIRROR="https://anne.media/mirror/anne-node"
RELONS_TABLE="relons_this_annode_only"

# -----------------------------------------------------------------------------
#  Presentation
# -----------------------------------------------------------------------------

if [ -t 1 ] && [ "${TERM:-dumb}" != "dumb" ]; then
  C_RESET=$'\033[0m'
  C_BOLD=$'\033[1m'
  C_DIM=$'\033[2m'
  C_RED=$'\033[31m'
  C_GREEN=$'\033[32m'
  C_YELLOW=$'\033[33m'
  C_CYAN=$'\033[36m'
  IS_TTY=1
else
  C_RESET= C_BOLD= C_DIM= C_RED= C_GREEN= C_YELLOW= C_CYAN=
  IS_TTY=0
fi

rule() {
  local char="${1:-━}" width="${2:-72}" line
  printf -v line '%*s' "$width" ''
  printf '%s%s%s\n' "$C_DIM" "${line// /$char}" "$C_RESET"
}

banner() {
  echo
  rule "═"
  printf '  %s%sAM·OS%s  %s│  annode upgrade%s\n' \
    "$C_BOLD" "$C_CYAN" "$C_RESET" "$C_DIM" "$C_RESET"
  rule "═"
  echo
}

step() {
  echo
  printf '%s▸%s  %s%s%s\n' "$C_CYAN" "$C_RESET" "$C_BOLD" "$1" "$C_RESET"
  rule "─"
}

say()  { printf '  %s\n' "$*"; }
ok()   { printf '  %s✓%s  %s\n' "$C_GREEN" "$C_RESET" "$*"; }
warn() { printf '  %s⚠%s  %s%s%s\n' "$C_YELLOW" "$C_RESET" "$C_YELLOW" "$*" "$C_RESET"; }
err()  { printf '  %s✗%s  %s%s%s\n' "$C_RED" "$C_RESET" "$C_RED" "$*" "$C_RESET"; }
info() { printf '  %s·%s  %s%s%s\n' "$C_CYAN" "$C_RESET" "$C_DIM" "$*" "$C_RESET"; }
kv()   { printf '  %s%-18s%s %s\n' "$C_DIM" "$1" "$C_RESET" "$2"; }

die()  { echo; err "$*"; echo; exit 1; }

# -----------------------------------------------------------------------------
#  Pre-flight
# -----------------------------------------------------------------------------

banner

[ "$(id -u)" -eq 0 ] || die "This script must run as root."

if [ "$RESTORESNAP" = "restore" ] && [ -z "$DB_ROOT_USER_PASS" ]; then
  err "Restore requires the MariaDB root password."
  echo
  say "Usage:"
  say "  $0                upgrade application only"
  say "  $0 restore PW     also restore annedb from the mirror snapshot"
  echo
  say "The password is in /root/mariadb_root_password.txt."
  exit 1
fi

[ -d "$ANNODE_DIR" ] || die "annode directory not found: $ANNODE_DIR"
[ -f "$ANNODE_SVC" ] || die "Service script not found: $ANNODE_SVC"
command -v mariadb     >/dev/null 2>&1 || die "mariadb client not found"
command -v mariadb-dump >/dev/null 2>&1 || die "mariadb-dump not found"
command -v unzip       >/dev/null 2>&1 || die "unzip not found"
command -v curl        >/dev/null 2>&1 || die "curl not found"

kv "Annode dir" "$ANNODE_DIR"
kv "Database"      "$ANNODE_DB"
kv "Service"       "$ANNODE_SVC"
if [ "$RESTORESNAP" = "restore" ]; then
  kv "Mode"        "app upgrade + database restore"
else
  kv "Mode"        "app upgrade only"
fi

# -----------------------------------------------------------------------------
#  Step 1 -- Stop annode
# -----------------------------------------------------------------------------

step "Stopping annode service"

if pgrep -u "$ANNODE_USER" -f anne-node >/dev/null 2>&1; then
  "$ANNODE_SVC" stop || warn "rc.annode stop returned non-zero"
  sleep 1
  if pgrep -u "$ANNODE_USER" -f anne-node >/dev/null 2>&1; then
    warn "Process still running; forcing"
    pkill -u "$ANNODE_USER" -f anne-node 2>/dev/null || true
    sleep 1
  fi
  ok "annode stopped"
else
  info "annode was not running"
fi

# -----------------------------------------------------------------------------
#  Step 2 -- Ensure mariadbd is up
# -----------------------------------------------------------------------------

if [ "$RESTORESNAP" = "restore" ]; then
  step "Checking MariaDB"

  if pgrep -x mariadbd >/dev/null 2>&1; then
    ok "mariadbd running"
  else
    info "mariadbd not running; starting via $MARIADB_SVC"
    "$MARIADB_SVC" start
    sleep 2
    pgrep -x mariadbd >/dev/null 2>&1 || die "mariadbd failed to start"
    ok "mariadbd started"
  fi
fi

# -----------------------------------------------------------------------------
#  Step 3 -- Restore annedb (optional)
# -----------------------------------------------------------------------------

if [ "$RESTORESNAP" = "restore" ]; then
  step "Restoring $ANNODE_DB from mirror"

  TMPD=$(mktemp -d /tmp/annode-upgrade.XXXXXX)
  trap 'rm -rf "$TMPD"' EXIT

  # -- 3a. Preserve the per-node relons table --
  relons_dump="$TMPD/localrelons.sql"
  has_relons=0

  if mariadb -u root -p"$DB_ROOT_USER_PASS" -D "$ANNODE_DB" -e \
       "SHOW TABLES LIKE '$RELONS_TABLE';" 2>/dev/null | grep -q "$RELONS_TABLE"; then
    has_relons=1
    info "Preserving table '$RELONS_TABLE'"
    mariadb-dump -u root -p"$DB_ROOT_USER_PASS" "$ANNODE_DB" "$RELONS_TABLE" \
      > "$relons_dump" \
      || die "Failed to dump $RELONS_TABLE"
    ok "saved to $relons_dump ($(du -h "$relons_dump" | cut -f1))"
  else
    info "No '$RELONS_TABLE' table; nothing to preserve"
  fi

  # -- 3b. Drop all tables and views --
  info "Dropping all tables and views in $ANNODE_DB"

  TABLES=$(mariadb -u root -p"$DB_ROOT_USER_PASS" -N -B \
             -e "SELECT table_name FROM information_schema.tables WHERE table_schema='$ANNODE_DB';" \
             | tr -d '\r')

  if [ -n "$TABLES" ]; then
    count=$(printf '%s\n' "$TABLES" | wc -l)
    info "  $count object(s) to drop"

    while IFS= read -r t; do
      [ -n "$t" ] || continue
      mariadb -u root -p"$DB_ROOT_USER_PASS" "$ANNODE_DB" \
        -e "SET FOREIGN_KEY_CHECKS=0; DROP TABLE IF EXISTS \`$t\`; SET FOREIGN_KEY_CHECKS=1;" \
        2>/dev/null || true
    done <<< "$TABLES"

    ok "database emptied"
  else
    info "  database already empty"
  fi

  # -- 3c. Download the fresh snapshot --
  snap_zip="$TMPD/annedb-latest.sql.zip"
  snap_sql="$TMPD/annedb-latest.sql"

  info "Downloading $MIRROR/annedb-latest.sql.zip"
  curl -fL --progress-bar -o "$snap_zip" "$MIRROR/annedb-latest.sql.zip" \
    || die "Download failed"

  info "Extracting"
  unzip -q -o "$snap_zip" -d "$TMPD" || die "unzip failed"
  [ -f "$snap_sql" ] || die "Expected $snap_sql after extraction"

  # -- 3d. Import --
  step "Importing snapshot into $ANNODE_DB"

  SQL_BYTES=$(stat -c %s "$snap_sql" 2>/dev/null || echo 0)
  SQL_MB=$(( SQL_BYTES / 1048576 ))
  info "SQL file: ${SQL_MB} MB... this may take a few minutes"

  import_start=$SECONDS
  if mariadb -u root -p"$DB_ROOT_USER_PASS" "$ANNODE_DB" < "$snap_sql"; then
    import_elapsed=$(( SECONDS - import_start ))
    ok "import complete in ${import_elapsed}s"
  else
    die "Import failed"
  fi

  # -- 3e. Restore the preserved relons table --
  if [ "$has_relons" -eq 1 ]; then
    info "Restoring local '$RELONS_TABLE'"
    mariadb -u root -p"$DB_ROOT_USER_PASS" "$ANNODE_DB" < "$relons_dump" \
      || die "Failed to restore $RELONS_TABLE"
    ok "'$RELONS_TABLE' restored"
  fi

  rm -rf "$TMPD"
  trap - EXIT
fi

# -----------------------------------------------------------------------------
#  Step 4 -- Fetch and install new application
# -----------------------------------------------------------------------------

step "Upgrading annode"

TMPD=$(mktemp -d /tmp/annode-upgrade.XXXXXX)
trap 'rm -rf "$TMPD"' EXIT

app_zip="$TMPD/anne-node.zip"

info "Downloading $MIRROR/anne-node.zip"
curl -fL --progress-bar -o "$app_zip" "$MIRROR/anne-node.zip" \
  || die "Download failed"

info "Preserving existing node.properties"
PROPS_BACKUP=""
if [ -f "$ANNODE_DIR/conf/node.properties" ]; then
  PROPS_BACKUP="$TMPD/node.properties.bak"
  cp -a "$ANNODE_DIR/conf/node.properties" "$PROPS_BACKUP"
  ok "backed up"
fi

info "Extracting into $ANNODE_DIR"
unzip -q -o "$app_zip" -d "$ANNODE_DIR" || die "unzip failed"

if [ -n "$PROPS_BACKUP" ]; then
  cp -a "$PROPS_BACKUP" "$ANNODE_DIR/conf/node.properties"
  ok "node.properties restored"
fi

info "Fixing ownership"
chown -R "$ANNODE_USER:$ANNODE_USER" "$ANNODE_DIR"
chown -R "$ANNODE_USER:$ANNODE_USER" "$ANNODE_HOME"
chmod 600 "$ANNODE_DIR/conf/node.properties" 2>/dev/null || true

rm -rf "$TMPD"
trap - EXIT

ok "application upgraded"

# -----------------------------------------------------------------------------
#  Step 5 -- Start annode
# -----------------------------------------------------------------------------

step "Starting annode service"

"$ANNODE_SVC" start || die "rc.annode start failed"

sleep 2
if pgrep -u "$ANNODE_USER" -f anne-node >/dev/null 2>&1; then
  ok "annode running"
else
  err "annode did not come up"
  [ -f "$ANNODE_LOG" ] && {
    info "Last lines of $ANNODE_LOG:"
    tail -n 20 "$ANNODE_LOG" | sed 's/^/      /'
  }
  exit 1
fi

# -----------------------------------------------------------------------------
#  Summary
# -----------------------------------------------------------------------------

echo
rule "═"
printf '  %s%sUpgrade complete%s\n' "$C_BOLD" "$C_GREEN" "$C_RESET"
rule "─"
kv "Application" "upgraded from $MIRROR/anne-node.zip"
if [ "$RESTORESNAP" = "restore" ]; then
  kv "Database"  "$ANNODE_DB restored from snapshot"
  [ "${has_relons:-0}" = "1" ] && kv "Preserved" "$RELONS_TABLE"
fi
kv "Service"     "annode running"
rule "═"
echo