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

# This script compares local package.json version with the version deployed on the production host.
# It expects these environment variables to be set in the CI environment:
# - PROD_HOST, PROD_USER, PROD_PORT
# - PROD_SSH_KEY (the private key)

if [ -z "${PROD_HOST:-}" ] || [ -z "${PROD_USER:-}" ] || [ -z "${PROD_PORT:-}" ]; then
  echo "Missing PROD_HOST / PROD_USER / PROD_PORT environment variables"
  exit 1
fi

if [ -z "${PROD_SSH_KEY:-}" ]; then
  echo "Missing PROD_SSH_KEY secret"
  exit 1
fi

mkdir -p ~/.ssh
printf "%s" "$PROD_SSH_KEY" > ~/.ssh/id_ed25519
chmod 600 ~/.ssh/id_ed25519

LOCAL_VERSION=$(node -p "require('./package.json').version")
echo "Local package.json version: $LOCAL_VERSION"

# Fetch remote package.json version (graceful fallback to 0.0.0)
REMOTE_VERSION=$(ssh -i ~/.ssh/id_ed25519 -p "$PROD_PORT" -o BatchMode=yes -o StrictHostKeyChecking=no "$PROD_USER@$PROD_HOST" \
  "grep '\"version\"' /var/www/harheimertc/package.json | head -1 | sed -E 's/.*\"version\":\s*\"([^\"]+)\".*/\\1/' || echo '0.0.0'")

echo "Remote production version: $REMOTE_VERSION"

# Compare versions using a small Node helper (semantic-ish: numeric dot-separated)
NODE_COMPARE='const a=process.env.LOCAL||"0.0.0"; const b=process.env.REMOTE||"0.0.0"; function cmp(x,y){const px=x.split(".").map(n=>parseInt(n||0,10)); const py=y.split(".").map(n=>parseInt(n||0,10)); const len=Math.max(px.length,py.length); for(let i=0;i<len;i++){const A=px[i]||0; const B=py[i]||0; if(A>B) return 1; if(A<B) return -1;} return 0;} const r=cmp(a,b); if(r<=0){ console.error(`Local version ${a} is not greater than production version ${b}`); process.exit(1);} else { console.log(`Local version ${a} is greater than production version ${b}`); process.exit(0);}'

LOCAL="$LOCAL_VERSION" REMOTE="$REMOTE_VERSION" node -e "$NODE_COMPARE"
