#!/bin/sh
# Updates the VodMax server from the GitHub releases: downloads the archive
# for this machine, checks it against the release's SHA256SUMS, keeps the
# running binary as vodmax-server.old, installs the new one and restarts
# the service.
#
#   sudo vodmax-update            the newest stable release (never older
#                                 than the installed one)
#   sudo vodmax-update v0.3.1     a given release: a beta, or to go back
#   sudo BETA=1 vodmax-update     the newest release, betas included
#
# Going back to the previous binary without downloading:
#   sudo mv /usr/local/bin/vodmax-server.old /usr/local/bin/vodmax-server
#   sudo systemctl restart vodmax
# If the new version changed the database, the previous one refuses it
# ("database creato da una versione più recente"): the server copied it
# before changing it, in <data>/pre-upgrade/vodmax-schemaN-<date>.db; put
# that copy in place of vodmax.db (service stopped) before going back.
set -eu

REPO=silirim/VodMax
BIN=${VODMAX_BIN:-/usr/local/bin/vodmax-server}
SERVICE=${VODMAX_SERVICE:-vodmax}

case $(uname -m) in
  x86_64 | amd64) arch=amd64 ;;
  aarch64 | arm64) arch=arm64 ;;
  armv7* | armv8l) arch=armv7 ;;
  *) echo "Architettura $(uname -m) non supportata." >&2; exit 1 ;;
esac
for tool in tar sha256sum; do
  command -v "$tool" >/dev/null || { echo "Serve $tool." >&2; exit 1; }
done
# get URL FILE (FILE "-" for standard output), with curl or wget.
if command -v curl >/dev/null; then
  get() { curl -fsSL -o "$2" "$1"; }
elif command -v wget >/dev/null; then
  get() { wget -q -O "$2" "$1"; }
else
  echo "Serve curl o wget." >&2; exit 1
fi

current=$("$BIN" -version 2>/dev/null | cut -d' ' -f2 || true)
tag=${1:-}
asked=$tag
if [ -z "$tag" ]; then
  # The newest stable release; with BETA=1 the newest of all, betas
  # included. Drafts are not public. A beta installed does not bring
  # other betas: they are chosen (BETA=1, or the tag).
  api="https://api.github.com/repos/$REPO/releases/latest"
  [ -n "${BETA:-}" ] && api="https://api.github.com/repos/$REPO/releases?per_page=1"
  tag=$(get "$api" - | sed -n 's/.*"tag_name": *"\([^"]*\)".*/\1/p' | head -n 1)
  [ -n "$tag" ] || { echo "Nessuna versione trovata su GitHub." >&2; exit 1; }
fi
case $tag in v*) ;; *) tag=v$tag ;; esac
# Without a tag, never back: "0.6.0" is newer than "0.6.0-beta.2", which is
# newer than "0.5.5".
if [ -z "$asked" ] && [ -n "$current" ]; then
  cur=${current#v}; new=${tag#v}
  cur_core=${cur%%[-+]*}; new_core=${new%%[-+]*}
  higher=$(printf '%s\n%s\n' "$cur_core" "$new_core" | sort -V | tail -n 1)
  if [ "$cur_core" != "$new_core" ] && [ "$higher" = "$cur_core" ] && [ -z "${FORCE:-}" ]; then
    echo "Hai già VodMax $current, più recente di $tag. Per installare una versione precisa: sudo vodmax-update <versione>."
    exit 0
  fi
fi
if [ "${current#v}" = "${tag#v}" ] && [ -z "${FORCE:-}" ]; then
  echo "VodMax $tag è già installato (FORCE=1 per reinstallarlo)."
  exit 0
fi

name=vodmax-server_${tag#v}_linux_$arch
base=https://github.com/$REPO/releases/download/$tag
tmp=$(mktemp -d)
trap 'rm -rf "$tmp"' EXIT INT TERM
echo "Scarico VodMax $tag ($arch)..."
get "$base/$name.tar.gz" "$tmp/$name.tar.gz" ||
  { echo "Versione $tag non trovata per $arch: niente è stato cambiato." >&2; exit 1; }
get "$base/SHA256SUMS" "$tmp/SHA256SUMS" ||
  { echo "SHA256SUMS di $tag non trovato: niente è stato cambiato." >&2; exit 1; }
(cd "$tmp" && grep " $name.tar.gz\$" SHA256SUMS > check && [ -s check ] && sha256sum -c check >/dev/null) ||
  { echo "Checksum non valido: niente è stato cambiato." >&2; exit 1; }
tar -xzf "$tmp/$name.tar.gz" -C "$tmp"
"$tmp/$name/vodmax-server" -version >/dev/null

[ -f "$BIN" ] && cp -p "$BIN" "$BIN.old"
install -m 755 "$tmp/$name/vodmax-server" "$BIN.new"
mv -f "$BIN.new" "$BIN"
# The script updates itself too (where it was started from).
case $0 in */*) self=$0 ;; *) self=$(command -v "$0" || true) ;; esac
[ -n "$self" ] && [ -f "$self" ] && [ -f "$tmp/$name/vodmax-update" ] && install -m 755 "$tmp/$name/vodmax-update" "$self"

systemctl restart "$SERVICE"
# Running for a few seconds, not just started: a database it cannot open
# stops it right away.
ok=
for _ in 1 2 3 4 5 6; do
  sleep 1
  systemctl is-active --quiet "$SERVICE" && ok=1 || { ok=; break; }
done
if [ -n "$ok" ]; then
  echo "Installato $("$BIN" -version). La versione precedente è in $BIN.old."
else
  echo "Il servizio non è ripartito: controlla 'journalctl -u $SERVICE'. Per tornare indietro:" >&2
  echo "  sudo mv $BIN.old $BIN && sudo systemctl restart $SERVICE" >&2
  echo "Se dice che il database è di una versione più recente, rimetti prima la copia in <dati>/pre-upgrade/." >&2
  exit 1
fi
