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

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

VERSION="${1:-}"

if [[ -z "$VERSION" ]]; then
  echo "Usage: ./release.sh <version>" >&2
  echo "Example: ./release.sh 1.0.9" >&2
  exit 1
fi

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

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

git add .
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
ssh "forge@${SATIS_SERVER_IP}" "cd /home/forge/satis && rm -rf /home/forge/.cache/composer/vcs/* && rm -rf public/* && php bin/satis build satis.json public/"

echo "Release v${VERSION} complete!"
