#!/usr/bin/env bash
set -euo pipefail
ETC=/etc/trinity-node-update; WORK=/var/lib/trinity-node-update; LOG=/var/log/trinity-node-update.log; SELF=/usr/local/sbin/trinity-node-update
ENTRY=/usr/local/lib/trinity-node-update/ssh-entry; ACCT=trinityupd; AHOME=/var/lib/trinityupd
SYSD="${WSP_NODEUPD_SYSTEMD:-/etc/systemd/system}"
die() { echo "WSPNODEUPDATE-FAILED $*"; log "FAILED $*"; exit 1; }
log() { printf '%s  %s\n' "$(date -u +%Y-%m-%dT%H:%M:%SZ)" "$*" >> "$LOG" 2>/dev/null || true; }
need_root() { [ "$(id -u)" -eq 0 ] || { echo "run with sudo" >&2; exit 1; }; }
comp() { local c; c="$(cat "$ETC/component" 2>/dev/null || true)"; case "$c" in recsrv|connsrv|vdigw) printf '%s' "$c";; *) return 1;; esac; }
field() { [ -r "$1" ] || return 0; sed -n "s/^$2=//p" "$1" 2>/dev/null | head -n1 || true; }
port() { [ -r "$SYSD/trinity-$1.service" ] || return 0; sed -n 's/^Environment=WSP_HTTPS_PORT=//p' "$SYSD/trinity-$1.service" 2>/dev/null | head -n1 || true; }
alive() { local p o; p="$(port "$1")"; [ -n "$p" ] || return 1; o="$(curl -sk --noproxy '*' --max-time 5 "https://127.0.0.1:$p/healthz" 2>/dev/null || true)"; [[ "$o" == *'"role"'* ]]; }
role() {
  local s=""
  case "$1" in
    vdigw) s="$(cat /var/lib/trinity-vdigw/keepalived.state 2>/dev/null || true)";;
    *) for f in /run/trinity-cluster/*.state; do [ -f "$f" ] && s="$(cat "$f")"; done;;
  esac
  case "$s" in MASTER) echo active;; BACKUP) echo standby;; FAULT|STOP) echo fault;; *) echo single;; esac
}

do_info() {
  local c; c="$(comp)" || { echo '{"error":"no TRINITY component on this server"}'; exit 1; }
  local v h=false; v="$(field "/opt/trinity-$c/VERSION" package)"; alive "$c" && h=true
  printf '{"component":"%s","package":"%s","node":"%s","role":"%s","healthy":%s,"updater":1}\n' "$c" "${v:-unknown}" "$(hostname -s | tr -cd 'A-Za-z0-9._-')" "$(role "$c")" "$h"
}

write_entry() {
  install -d -m 755 /usr/local/lib/trinity-node-update
  cat > "$ENTRY" <<'EN'
#!/bin/sh
set -f
# shellcheck disable=SC2086
set -- $SSH_ORIGINAL_COMMAND
case "${1:-}" in
  info) exec sudo -n /usr/local/sbin/trinity-node-update info ;;
  update) exec sudo -n /usr/local/sbin/trinity-node-update update "${2:-}" "${3:-}" "${4:-}" ;;
  *) echo "WSPNODEUPDATE-FAILED this key can only ask for info and send an update" ; exit 2 ;;
esac
EN
  chmod 755 "$ENTRY"; chown root:root "$ENTRY"
}

apply() {
  local d="$1" c="$2" svc="trinity-$2" opt="/opt/trinity-$2" unit="$SYSD/trinity-$2.service" nv ov
  [ -x "$d/app/trinity-portal" ] && [ -f "$d/trinity-$c.service" ] && [ -f "$d/trinity-$c" ] || die "the package has no program, unit or tool for $c"
  [ -d "$opt/app" ] && [ -f "$unit" ] || die "$c is not installed on this server - use its installer first"
  nv="$(field "$d/VERSION" package)"; ov="$(field "$opt/VERSION" package)"
  echo "== $c ${ov:-?} -> ${nv:-?}"; log "apply $c ${ov:-?} -> ${nv:-?}"
  local hp pp; hp="$(sed -n 's/^Environment=WSP_HTTPS_PORT=//p' "$unit" | head -n1)"; pp="$(sed -n 's/^Environment=WSP_HTTP_PORT=//p' "$unit" | head -n1)"
  cp -p "$unit" "$WORK/unit.old"
  install -m 644 "$d/trinity-$c.service" "$unit.new"
  [ -n "$hp" ] && sed -i "s/^Environment=WSP_HTTPS_PORT=.*/Environment=WSP_HTTPS_PORT=$hp/" "$unit.new"
  [ -n "$pp" ] && sed -i "s/^Environment=WSP_HTTP_PORT=.*/Environment=WSP_HTTP_PORT=$pp/" "$unit.new"
  echo "== program"
  rm -rf "$opt/app.new" && cp -a "$d/app" "$opt/app.new" && chmod 755 "$opt/app.new/trinity-portal"
  rm -rf "$opt/app.old"; mv "$opt/app" "$opt/app.old"; mv "$opt/app.new" "$opt/app"; mv -f "$unit.new" "$unit"
  install -m 755 "$d/trinity-$c" "/usr/local/bin/trinity-$c"
  if [ "$c" = vdigw ] && [ -d /usr/local/lib/trinity-vdigw ]; then
    install -o root -g root -m 755 "$d/trinity-vdigw-check" /usr/local/lib/trinity-vdigw/check; install -o root -g root -m 755 "$d/trinity-vdigw-notify" /usr/local/lib/trinity-vdigw/notify
  fi
  if [ "$c" = connsrv ] && [ -f "$d/trinity-guacd.sh" ] && [ -f /usr/local/share/trinity-guacd.build ]; then
    local want have; want="$(sed -n 's/^BUILD_ID="\([^"]*\)".*/\1/p' "$d/trinity-guacd.sh" | head -n1)"; have="$(cat /usr/local/share/trinity-guacd.build 2>/dev/null || true)"
    if [ -n "$want" ] && [ "$have" != "$want" ]; then echo "== guacd build '$have' differs from '$want' - rebuilding (several minutes)"; bash "$d/trinity-guacd.sh" 9>&- || echo "WARNING: guacd was not rebuilt - run trinity-guacd.sh on this server"; fi
  fi
  if [ "$c" = connsrv ] && getent group guacd >/dev/null && [ -d /var/lib/guacamole/recordings ]; then
    install -d -o guacd -g guacd -m 2770 /var/lib/guacamole/recordings/vdi
    find /var/lib/guacamole/recordings -mindepth 1 -type d -exec chgrp guacd {} + -exec chmod 2770 {} +
    if [ -d /var/lib/guacamole/drive ]; then install -d -o guacd -g guacd -m 0750 /var/lib/guacamole/drive/vdi; fi
  fi
  if [ -f "$d/trinity-net-tuning.sh" ] && [ "$c" != recsrv ]; then install -m 755 "$d/trinity-net-tuning.sh" /usr/local/sbin/trinity-net-tuning.sh; bash "$d/trinity-net-tuning.sh" apply || true; fi
  echo "== service"
  systemctl daemon-reload 9>&-; systemctl restart "$svc" 9>&-
  local ok=0 i; for i in $(seq 1 90); do if alive "$c"; then ok=1; break; fi; sleep 2; done
  if [ "$ok" != 1 ]; then
    echo "== the service does not answer - putting the previous program back"; log "rollback $c"
    rm -rf "$opt/app.failed"; mv "$opt/app" "$opt/app.failed"; mv "$opt/app.old" "$opt/app"; cp -p "$WORK/unit.old" "$unit"
    systemctl daemon-reload 9>&-; systemctl restart "$svc" 9>&- || true
    local mb=""; [ -f "/etc/trinity-$c/migrated-from-mwsmon" ] && mb="$(sed -n 's/^backup=//p' "/etc/trinity-$c/migrated-from-mwsmon" | head -n1)"
    [ -n "$mb" ] && [ -f "$mb/rollback.sh" ] && echo "this server was moved from MWSMON just before - to go back to MWSMON as it was: sudo bash $mb/rollback.sh"
    die "the new program did not answer within 3 minutes; the previous one was put back (the failed one is in $opt/app.failed)"
  fi
  install -m 644 "$d/VERSION" "$opt/VERSION"
  install -m 644 "$d/trinity-release-signing.pub" "$ETC/vendor.pub"
  install -m 755 "$d/trinity-node-update" "$SELF.new" && mv -f "$SELF.new" "$SELF"
  write_entry
  log "applied $c ${nv:-?}"
}

do_update() {
  local ver="${1:-}" sha="${2:-}" sig="${3:-}" c
  early() { cat > /dev/null 2>&1 || true; die "$@"; }
  c="$(comp)" || early "no TRINITY component on this server"
  [[ "$ver" =~ ^[0-9]{1,4}(\.[0-9]{1,5}){1,3}$ ]] || early "version"
  [[ "$sha" =~ ^[0-9a-f]{64}$ ]] || early "sha256"
  [[ "$sig" =~ ^[A-Za-z0-9+/=]{100,1400}$ ]] || early "signature"
  [ -s "$ETC/vendor.pub" ] || early "no vendor key on this server ($ETC/vendor.pub)"
  install -d -m 700 "$WORK"; exec 9>"$WORK/lock"; flock -n 9 || early "another update is running on this server"
  local in="$WORK/incoming"; rm -rf "$in"; install -d -m 700 "$in"
  log "update $c $ver from ${SUDO_USER:-?} ${SSH_CLIENT:-}"
  head -c $((1024 * 1024 * 1024 + 1)) > "$in/pkg.tar.gz"
  local size got; size="$(stat -c %s "$in/pkg.tar.gz")"
  [ "$size" -gt 1024 ] && [ "$size" -le $((1024 * 1024 * 1024)) ] || { rm -rf "$in"; die "the package is empty or larger than 1 GB"; }
  got="$(sha256sum "$in/pkg.tar.gz" | cut -d' ' -f1)"
  [ "$got" = "$sha" ] || { rm -rf "$in"; die "the package arrived damaged (SHA-256 differs)"; }
  printf 'mwsmon-node-v1\n%s\n%s\n%s\n' "$c" "$ver" "$sha" > "$in/msg"
  printf '%s' "$sig" | openssl base64 -d -A -out "$in/sig.bin" 2>/dev/null || { rm -rf "$in"; die "signature"; }
  openssl dgst -sha256 -verify "$ETC/vendor.pub" -signature "$in/sig.bin" "$in/msg" >/dev/null 2>&1 || { rm -rf "$in"; die "the vendor signature does not match this package, version and component - nothing was installed"; }
  local have; have="$(field "/opt/trinity-$c/VERSION" package)"
  if [ -n "$have" ] && [ "$have" != "$ver" ] && [ "$(printf '%s\n%s\n' "$have" "$ver" | sort -V | tail -n1)" = "$have" ]; then rm -rf "$in"; die "this server has $have - the older $ver is not installed"; fi
  if tar -tzf "$in/pkg.tar.gz" | grep -q -v -E "^$c(/|\$)" || tar -tzf "$in/pkg.tar.gz" | grep -q -E '(^|/)\.\.(/|$)'; then rm -rf "$in"; die "this is not a $c package"; fi
  install -d -m 700 "$in/x"; tar -xzf "$in/pkg.tar.gz" --no-same-owner -C "$in/x"
  [ "$(field "$in/x/$c/VERSION" component)" = "$c" ] && [ "$(field "$in/x/$c/VERSION" package)" = "$ver" ] || { rm -rf "$in"; die "the package says another component or version than the signature"; }
  echo "== signature and SHA-256 are right: $c $ver"
  apply "$in/x/$c" "$c"
  rm -rf "$in"
  echo "WSPNODEUPDATE-OK $ver"
}

do_setup() {
  local d="$1" c="$2"; shift 2
  install -d -m 755 "$ETC" /usr/local/lib/trinity-node-update; install -d -m 700 "$WORK"
  printf '%s\n' "$c" > "$ETC/component"
  install -m 644 "$d/trinity-release-signing.pub" "$ETC/vendor.pub"
  [ -f "$d/VERSION" ] && install -m 644 "$d/VERSION" "/opt/trinity-$c/VERSION"
  install -m 755 "$d/trinity-node-update" "$SELF.new" && mv -f "$SELF.new" "$SELF"
  write_entry
  [ $# -gt 0 ] && do_access "$@"
  return 0
}

do_access() {
  local key="" from="" mode=set
  while [ $# -gt 0 ]; do case "$1" in --key) key="$2"; shift 2;; --from) from="$2"; shift 2;; --show) mode=show; shift;; --remove) mode=remove; shift;; *) echo "unknown option $1" >&2; exit 2;; esac; done
  local ak="$AHOME/.ssh/authorized_keys"
  [ "$mode" = set ] && write_entry
  if [ "$mode" = show ]; then
    if [ -s "$ak" ]; then echo "TRINITY may update this server. Key: $(ssh-keygen -lf "$ak" 2>/dev/null | head -n1)"; sed -n 's/.*from="\([^"]*\)".*/Allowed from: \1/p' "$ak"; else echo "No update key: TRINITY cannot update this server."; fi
    return 0
  fi
  if [ "$mode" = remove ]; then rm -f "$ak" /etc/sudoers.d/trinity-node-update; echo "Update access removed."; log "access removed"; return 0; fi
  [[ "$key" =~ ^(ssh-rsa|ssh-ed25519|ecdsa-sha2-nistp[0-9]+)\ [A-Za-z0-9+/=]{60,1000}(\ [A-Za-z0-9@._:-]{0,100})?$ ]] || { echo "--key: the public key line TRINITY shows (ssh-rsa AAAA...)" >&2; exit 2; }
  [ -z "$from" ] || [[ "$from" =~ ^[0-9A-Fa-f.:,/*-]{1,400}$ ]] || { echo "--from: addresses, comma separated" >&2; exit 2; }
  command -v sudo >/dev/null 2>&1 || { apt-get update -qq; DEBIAN_FRONTEND=noninteractive apt-get install -y -qq sudo >/dev/null; }
  id "$ACCT" >/dev/null 2>&1 || useradd --system --home-dir "$AHOME" --shell /bin/sh "$ACCT"
  install -d -o root -g root -m 755 "$AHOME" "$AHOME/.ssh"
  local opts="restrict,command=\"$ENTRY\""; [ -n "$from" ] && opts="restrict,from=\"$from\",command=\"$ENTRY\""
  printf '%s %s\n' "$opts" "$key" > "$ak.tmp"; chown root:root "$ak.tmp"; chmod 644 "$ak.tmp"; mv -f "$ak.tmp" "$ak"
  printf '# written by trinity-node-update: TRINITY component updates\n%s ALL=(root) NOPASSWD: %s info, %s update *\n' "$ACCT" "$SELF" "$SELF" > /etc/sudoers.d/trinity-node-update.tmp
  chmod 440 /etc/sudoers.d/trinity-node-update.tmp
  if command -v visudo >/dev/null 2>&1 && ! visudo -cf /etc/sudoers.d/trinity-node-update.tmp >/dev/null; then rm -f /etc/sudoers.d/trinity-node-update.tmp; echo "the sudo rule is not valid on this system - update access was not set" >&2; exit 1; fi
  mv -f /etc/sudoers.d/trinity-node-update.tmp /etc/sudoers.d/trinity-node-update
  echo "TRINITY may now send vendor-signed updates to this server (account $ACCT, key $(ssh-keygen -lf "$ak" 2>/dev/null | awk '{print $2}')${from:+, only from $from})."
  log "access set${from:+ from $from}"
}

case "${1:-}" in
  info) need_root; do_info ;;
  update) need_root; shift; do_update "$@" ;;
  apply-local) need_root; c="$(comp)" || { echo "this server has no TRINITY component with the update tool - run the installer without --update once" >&2; exit 1; }
               install -d -m 700 "$WORK"; apply "$2" "$c"; echo "WSPNODEUPDATE-OK $(field "/opt/trinity-$c/VERSION" package)" ;;
  setup) need_root; shift; do_setup "$@" ;;
  access) need_root; shift; do_access "$@" ;;
  *) cat <<'TRINITY_USAGE'; exit 2 ;;
  /usr/local/sbin/trinity-node-update (root). TRINITY -> Settings -> Portal setup -> Component updates sends a new package over SSH; this
  trinity-node-update access --show | --remove
  trinity-node-update info
  trinity-node-update apply-local <unpacked package folder>     (what "install-...sh --update" runs)
Documentation: https://mobileworkplaceservices.ro/docs.html
TRINITY_USAGE
esac
