#!/usr/bin/env bash
set -euo pipefail

INSTALL_DIR="${ALOMOTION_DIR:-/opt/alomotion}"
SERVICE_NAME="alomotion"
SERVICE_FILE="/etc/systemd/system/${SERVICE_NAME}.service"

if [[ "${EUID}" -eq 0 ]]; then
  SUDO=""
else
  SUDO="sudo"
fi

cmd="${1:-help}"
shift || true

usage() {
  local ver
  ver="$(cat "$INSTALL_DIR/VERSION" 2>/dev/null || echo 'unknown')"
  cat <<EOF
alomotion v${ver} — Code-to-Video Studio & Render Engine
Official Web : https://alomotion.my.id
Creator      : https://aldih.com
Cloud VPS    : https://cloud.aldih.com (NAT VPS & Pterodactyl Panel)
Partner      : https://warungaldi.com

Commands:
  alomotion status                     Cek status service systemd
  alomotion start | stop | restart     Kontrol service alomotion
  alomotion logs                       Lihat log real-time
  alomotion version                    Tampilkan versi terpasang
  alomotion reset-password             Ganti password login web
  alomotion upgrade <zip|url|github>   Upgrade tanpa menghapus data user
  alomotion render [options...]        Render video via CLI
  alomotion uninstall [--yes]          Hapus bersih alomotion & systemd
EOF
}

do_upgrade() {
  local src="${1:-}"
  local tmpdir
  tmpdir="$(mktemp -d /tmp/alomotion-upgrade.XXXXXX)"
  trap 'rm -rf "$tmpdir"' EXIT

  if [[ -z "$src" ]]; then
    if [[ -d "$INSTALL_DIR/.git" ]]; then
      git -C "$INSTALL_DIR" pull --ff-only
      bash "$INSTALL_DIR/run.sh" --upgrade
      return 0
    else
      echo "Usage: alomotion upgrade <file.zip | url-zip | github-url>"
      exit 1
    fi
  fi

  local extracted=""
  if [[ "$src" =~ ^https?://.*\.git$ ]] || [[ "$src" =~ ^https?://github\.com/[^/]+/[^/]+/?$ ]]; then
    git clone --depth 1 "$src" "$tmpdir/repo"
    extracted="$tmpdir/repo"
  elif [[ "$src" =~ ^https?:// ]]; then
    curl -fsSL "$src" -o "$tmpdir/pkg.zip"
    unzip -q "$tmpdir/pkg.zip" -d "$tmpdir/unpack"
    extracted="$tmpdir/unpack"
  elif [[ -f "$src" ]]; then
    unzip -q "$src" -d "$tmpdir/unpack"
    extracted="$tmpdir/unpack"
  elif [[ -d "$src" ]]; then
    extracted="$src"
  else
    echo "[ERROR] Sumber upgrade tidak ditemukan: $src"
    exit 1
  fi

  local root_dir=""
  if [[ -f "$extracted/server.js" && -f "$extracted/run.sh" ]]; then
    root_dir="$extracted"
  else
    local found
    found="$(find "$extracted" -maxdepth 3 -name "server.js" | head -n 1 || true)"
    [[ -n "$found" ]] && root_dir="$(dirname "$found")"
  fi

  if [[ -z "$root_dir" || ! -f "$root_dir/run.sh" ]]; then
    echo "[ERROR] Paket upgrade tidak valid."
    exit 1
  fi

  chmod +x "$root_dir/run.sh" "$root_dir/setup.sh"
  bash "$root_dir/run.sh" --upgrade
}

do_uninstall() {
  local auto_yes=0
  [[ "${1:-}" == "--yes" || "${1:-}" == "-y" ]] && auto_yes=1
  if [[ "$auto_yes" -eq 0 ]]; then
    echo "PERINGATAN: Menghapus service systemd, /usr/local/bin/alomotion, dan ${INSTALL_DIR}."
    read -r -p "Ketik 'HAPUS' untuk melanjutkan: " confirm
    [[ "$confirm" != "HAPUS" ]] && echo "Dibatalkan." && exit 0
  fi

  $SUDO systemctl stop "$SERVICE_NAME" 2>/dev/null || true
  $SUDO systemctl disable "$SERVICE_NAME" 2>/dev/null || true
  $SUDO rm -f "$SERVICE_FILE"
  $SUDO systemctl daemon-reload 2>/dev/null || true
  $SUDO systemctl reset-failed 2>/dev/null || true
  $SUDO rm -rf "$INSTALL_DIR"
  $SUDO rm -f /usr/local/bin/alomotion
  echo "alomotion telah dihapus bersih."
}

case "$cmd" in
  status)         $SUDO systemctl status "$SERVICE_NAME" --no-pager ;;
  start|stop|restart) $SUDO systemctl "$cmd" "$SERVICE_NAME" && echo "alomotion ${cmd}: OK" ;;
  logs)           $SUDO journalctl -u "$SERVICE_NAME" -f ;;
  version|-v|--version) echo "alomotion v$(cat "$INSTALL_DIR/VERSION" 2>/dev/null || echo 'unknown')" ;;
  reset-password) bash "$INSTALL_DIR/setup.sh" --upgrade --reset-password && $SUDO systemctl restart "$SERVICE_NAME" 2>/dev/null || true ;;
  upgrade|update) do_upgrade "$@" ;;
  render)         exec node "$INSTALL_DIR/cli.js" "$@" ;;
  uninstall)      do_uninstall "$@" ;;
  *)              usage ;;
esac
