#!/usr/bin/env bash
# Helpers inside an existing MyOffice LXC (runtime + Postgres + Gitea release app).
# Usage:
#   /opt/myoffice/proxmox/update.sh              # download latest/tag release + restart
#   /opt/myoffice/proxmox/update.sh upgrade
#   /opt/myoffice/proxmox/update.sh logs
#   /opt/myoffice/proxmox/update.sh restart
#   /opt/myoffice/proxmox/update.sh status

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
APP_DIR="$(cd "${SCRIPT_DIR}/.." && pwd)"
API_DIR="${APP_DIR}/api"
ACTION="${1:-upgrade}"

# shellcheck disable=SC1091
[[ -f "${SCRIPT_DIR}/env" ]] && . "${SCRIPT_DIR}/env"

export APP_DIR API_DIR
export GITEA_URL="${GITEA_URL:-}"
export GITEA_OWNER="${GITEA_OWNER:-}"
export GITEA_REPO="${GITEA_REPO:-myoffice-public}"
export RELEASE_TAG="${RELEASE_TAG:-latest}"
export RELEASE_ASSET_URL="${RELEASE_ASSET_URL:-}"
export GITEA_TOKEN="${GITEA_TOKEN:-}"

upgrade_app() {
  systemctl stop myoffice-api 2>/dev/null || true
  # shellcheck disable=SC1091
  source "${SCRIPT_DIR}/fetch-release.sh"
  download_and_extract
  systemctl start myoffice-api
  systemctl status myoffice-api --no-pager || true
}

case "$ACTION" in
  upgrade | update | rebuild | up)
    upgrade_app
    ;;
  logs)
    journalctl -u myoffice-api -f
    ;;
  restart)
    systemctl restart myoffice-api
    systemctl status myoffice-api --no-pager
    ;;
  status)
    systemctl status myoffice-api --no-pager || true
    if [[ ! -f "${API_DIR}/MyOffice.Web.dll" ]]; then
      echo
      echo "No app binaries. Run: $0 upgrade"
      echo "Or set GITEA_URL / GITEA_OWNER / RELEASE_TAG in ${SCRIPT_DIR}/env"
    fi
    ;;
  *)
    echo "Usage: $0 [upgrade|status|logs|restart]" >&2
    exit 1
    ;;
esac
