#!/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"

if [[ $# -ne 1 ]]; then
  echo "usage: $0 pushy-server@<version>" >&2
  exit 2
fi
package_spec=$1
[[ "$package_spec" == pushy-server@* ]] || { echo "unexpected package: $package_spec" >&2; exit 2; }

install_root=/opt/pushy
default_bun=$install_root/runtime/bun
if [[ ! -x "$default_bun" ]]; then
  default_bun=$(command -v bun || true)
fi
bun_bin=${PUSHY_BUN_BIN:-$default_bun}
env_file=$(resolve_env_file pushy-api.service "${PUSHY_ENV_FILE:-}")
download_root=$(mktemp -d "$install_root/releases/.download-XXXXXX")
trap 'rm -rf "$download_root"' EXIT

[[ -x "$bun_bin" ]] || { echo "bun executable not found; set PUSHY_BUN_BIN" >&2; exit 1; }

BUN_INSTALL="$download_root/bun" "$bun_bin" install -g --force "$package_spec"
package_dir="$download_root/bun/install/global/node_modules/pushy-server"
[[ -f "$package_dir/lib/index.js" ]] || { echo "installed package is incomplete" >&2; exit 1; }

"$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"
release_id=$("$bun_bin" -e "console.log(require('$package_dir/package.json').version)")
"$package_dir/deploy/systemd/install-release.sh" "$package_dir" "$release_id" "$bun_bin" "$env_file"
