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

# Satis / Forge server IP — update before releasing
SATIS_SERVER_IP="159.65.202.73"

FULL_SATIS_REBUILD=0
POSITIONAL=()
for arg in "$@"; do
  case "$arg" in
    --full-satis) FULL_SATIS_REBUILD=1 ;;
    *)
      POSITIONAL+=("$arg")
      ;;
  esac
done

VERSION="${POSITIONAL[0]:-}"

if [[ -z "$VERSION" || ${#POSITIONAL[@]} -ne 1 ]]; then
  echo "Usage: ./release.sh [--full-satis] <version>" >&2
  echo "       ./release.sh <version> [--full-satis]" >&2
  echo "Examples: ./release.sh 1.0.9   |   npm run release -- 1.0.9 --full-satis" >&2
  echo "          --full-satis: wipe Composer VCS cache + Satis public/, full mirror rebuild" >&2
  exit 1
fi

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
cd "$SCRIPT_DIR"

# Commit any pending changes first
if ! git diff --quiet || ! git diff --cached --quiet || \
   [[ -n "$(git ls-files --others --exclude-standard)" ]]; then
  git add -A
  git commit -m "chore: pre-release changes for v${VERSION}"
fi

export RELEASE_VERSION="$VERSION"
node <<'EOS'
const fs = require('fs');

const ver = process.env.RELEASE_VERSION;
for (const [file, indent] of [
  ['package.json', 2],
  ['composer.json', 4],
]) {
  const o = JSON.parse(fs.readFileSync(file, 'utf8'));
  o.version = ver;
  fs.writeFileSync(file, JSON.stringify(o, null, indent) + '\n');
}
EOS

# Stage only version files (avoids `git add .` scanning the whole tree — on some
# setups that can SIGBUS if the index is corrupt or a path triggers a git bug).
git add package.json composer.json
git diff --cached --quiet && {
  echo "No version change to commit (files already at v${VERSION})?" >&2
  exit 1
}
git commit -m "chore: release v${VERSION}"
git tag "v${VERSION}"
git push origin main
git push origin "v${VERSION}"
npm publish --registry http://maestro-npm.build2connect.nl --access public

if [[ "$FULL_SATIS_REBUILD" -eq 1 ]]; then
  echo "Running full Satis rebuild (Composer VCS cache + public/ wiped)…" >&2
  ssh "forge@${SATIS_SERVER_IP}" "cd /home/forge/satis && rm -rf /home/forge/.cache/composer/vcs/* public/* && php bin/satis build satis.json public/"
else
  ssh "forge@${SATIS_SERVER_IP}" "cd /home/forge/satis && php bin/satis build satis.json public/"
fi

echo "Release v${VERSION} complete!"
