#!/bin/bash
# ============================================================================
# publish.sh - Upload a new package version to your registry
# ============================================================================
# Run this from your LOCAL machine (where you build .s9pk files).
#
# Usage:
#   ./scripts/publish.sh <package-id> <s9pk-file> [vps-host]
#
# Examples:
#   ./scripts/publish.sh recap ./recap_x86_64.s9pk
#   ./scripts/publish.sh recap ./recap_x86_64.s9pk root@123.45.67.89
#
# What it does:
#   1. Uploads the .s9pk file to the VPS
#   2. Signals the registry to reload its config
#
# IMPORTANT: Before running this, update the version in
#   packages/<id>/package.json on the VPS (or locally then scp).
# ============================================================================

set -euo pipefail

PKG_ID="${1:?Usage: publish.sh <package-id> <s9pk-file> [vps-host]}"
S9PK_FILE="${2:?Usage: publish.sh <package-id> <s9pk-file> [vps-host]}"
VPS_HOST="${3:-root@5.161.191.254}"

REMOTE_DIR="/opt/startos-registry/packages/$PKG_ID"

if [ ! -f "$S9PK_FILE" ]; then
    echo "Error: File not found: $S9PK_FILE"
    exit 1
fi

S9PK_BASENAME="$(basename "$S9PK_FILE")"
S9PK_SIZE="$(du -h "$S9PK_FILE" | cut -f1)"

echo ""
echo "  Publishing to StartOS Registry"
echo "  ==============================="
echo "  Package:  $PKG_ID"
echo "  File:     $S9PK_BASENAME ($S9PK_SIZE)"
echo "  Target:   $VPS_HOST:$REMOTE_DIR"
echo ""

# Upload the .s9pk
echo "[1/3] Uploading $S9PK_BASENAME..."
scp "$S9PK_FILE" "$VPS_HOST:$REMOTE_DIR/$S9PK_BASENAME"

# Copy updated package.json if it exists locally
LOCAL_PKG_JSON="./packages/$PKG_ID/package.json"
if [ -f "$LOCAL_PKG_JSON" ]; then
    echo "[2/3] Uploading updated package.json..."
    scp "$LOCAL_PKG_JSON" "$VPS_HOST:$REMOTE_DIR/package.json"
else
    echo "[2/3] No local package.json found, skipping config upload."
    echo "  Make sure to update the version in $REMOTE_DIR/package.json on the VPS!"
fi

# Reload the registry (SIGHUP triggers config reload without downtime)
echo "[3/3] Reloading registry..."
ssh "$VPS_HOST" "systemctl reload startos-registry"

echo ""
echo "  Done! Package $PKG_ID published."
echo "  Verify: https://registry.satsflows.com/package/v0/version/$PKG_ID"
echo ""
