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

script_path=$(realpath "${BASH_SOURCE[0]}")
script_dir=$(dirname "$script_path")
source "$script_dir/resolve-env-file.sh"

usage() {
  cat <<'EOF'
usage: pushy-systemd-install [--bun-bin PATH] [--env-file PATH] [--worker|--no-worker]

Install the globally installed pushy-server package as versioned systemd
services, run its idempotent database migration, and start or roll the node.
EOF
}

bun_bin=${PUSHY_BUN_BIN:-$(command -v bun || true)}
env_file=${PUSHY_ENV_FILE:-}
worker_enabled=

while [[ $# -gt 0 ]]; do
  case "$1" in
    --bun-bin)
      bun_bin=${2:?missing value for --bun-bin}
      shift 2
      ;;
    --env-file)
      env_file=${2:?missing value for --env-file}
      shift 2
      ;;
    --worker)
      worker_enabled=true
      shift
      ;;
    --no-worker)
      worker_enabled=false
      shift
      ;;
    -h|--help)
      usage
      exit 0
      ;;
    *)
      echo "unknown option: $1" >&2
      usage >&2
      exit 2
      ;;
  esac
done

env_file=$(resolve_env_file pushy-api.service "$env_file")
[[ $EUID -eq 0 ]] || { echo "run this command with sudo" >&2; exit 1; }
[[ -x "$bun_bin" ]] || { echo "bun executable not found; pass --bun-bin" >&2; exit 1; }

if [[ -z "$worker_enabled" ]]; then
  if [[ -e /etc/pushy/worker-disabled ]]; then
    worker_enabled=false
  else
    worker_enabled=true
  fi
fi

package_dir=$(realpath "$(dirname "$script_path")/../..")
[[ -f "$package_dir/lib/index.js" ]] || { echo "incomplete pushy-server package: $package_dir" >&2; exit 1; }

release_id=$("$bun_bin" -e 'console.log(require(process.argv[1]).version)' "$package_dir/package.json")
previous_release=$(readlink -f /opt/pushy/current 2>/dev/null || true)
previous_bun=$(readlink -f /opt/pushy/runtime/bun 2>/dev/null || true)
was_active=false
was_worker_active=false
worker_was_disabled=false
if systemctl is-active --quiet pushy.target; then
  was_active=true
fi
if systemctl is-active --quiet pushy-worker.service; then
  was_worker_active=true
fi
if [[ -e /etc/pushy/worker-disabled ]]; then
  worker_was_disabled=true
fi

rollback() {
  result=$?
  trap - ERR
  set +e
  echo "deployment failed; restoring previous Pushy release" >&2
  if [[ -n "$previous_release" && -d "$previous_release" ]]; then
    ln -sfn "$previous_release" /opt/pushy/current.next
    mv -Tf /opt/pushy/current.next /opt/pushy/current
    if [[ -n "$previous_bun" && -x "$previous_bun" ]]; then
      ln -sfn "$previous_bun" /opt/pushy/runtime/bun.next
      mv -Tf /opt/pushy/runtime/bun.next /opt/pushy/runtime/bun
    fi
    install -d -m 0755 /etc/pushy
    if [[ "$worker_was_disabled" == true ]]; then
      touch /etc/pushy/worker-disabled
    else
      rm -f /etc/pushy/worker-disabled
    fi
    systemctl daemon-reload
    if [[ "$was_worker_active" == true ]]; then
      systemctl restart pushy-worker.service
    else
      systemctl stop pushy-worker.service
    fi
    systemctl stop pushy-api-candidate.service pushy-api-peer.service
    systemctl restart pushy-api.service
  elif [[ "$was_active" == false ]]; then
    systemctl stop pushy.target
  fi
  exit "$result"
}
trap rollback ERR

"$bun_bin" --env-file="$env_file" "$package_dir/lib/migrate-add-platform-task-retry.js"
"$bun_bin" --env-file="$env_file" "$package_dir/lib/migrate-add-client-event-package-version.js"
"$package_dir/deploy/systemd/install-release.sh" \
  "$package_dir" "$release_id" "$bun_bin" "$env_file" "$worker_enabled"

"$package_dir/deploy/systemd/roll-api.sh" "$release_id"
if [[ "$was_active" == true ]]; then
  if [[ "$worker_enabled" == true ]]; then
    systemctl restart pushy-worker.service
  else
    systemctl stop pushy-worker.service
  fi
else
  systemctl start pushy.target
fi
systemctl start pushy-dailyjob.timer pushy-cresc-ai-marketing.timer pushy-health-watchdog.timer

healthy=false
for _ in $(seq 1 30); do
  if curl --fail --silent --show-error --max-time 2 \
    http://127.0.0.1:9000/status >/dev/null 2>&1; then
    healthy=true
    break
  fi
  sleep 1
done
if [[ "$healthy" != true ]]; then
  echo "Pushy health check did not recover" >&2
  false
fi

"/opt/pushy/current/deploy/systemd/status.sh"
trap - ERR
echo "Pushy deployment complete: $release_id"
