#!/bin/bash
#
# Canonical release.sh for an adompkg source repo.
#
# Reads version from package.json, optionally bumps it (--bump patch|minor|major),
# runs build.sh if present, then runs `adompkg publish` and prints the resulting
# package URL.
#
# Usage:
#   ADOMPKG_TOKEN=<carbon-api-key> ./release.sh                # publish current version
#   ADOMPKG_TOKEN=<carbon-api-key> ./release.sh --bump patch   # bump + publish
#
set -euo pipefail

DIR="$(cd "$(dirname "$0")" && pwd)"
cd "$DIR"

if [ ! -f package.json ]; then
  echo "release.sh: no package.json found in $DIR" >&2
  exit 1
fi

REGISTRY="${ADOMPKG_REGISTRY:-https://git-wiki-ktqxite5iglh.adom.cloud}"

if [ -z "${ADOMPKG_TOKEN:-}" ]; then
  if [ -r /var/run/adom/api-key ]; then
    ADOMPKG_TOKEN="$(cat /var/run/adom/api-key)"
    export ADOMPKG_TOKEN
  else
    echo "release.sh: ADOMPKG_TOKEN is required (set ADOMPKG_TOKEN=<carbon-api-key>)" >&2
    exit 1
  fi
fi

# Read current version.
CUR_VERSION=$(node -e "console.log(require('./package.json').version)")
SLUG=$(node -e "console.log(require('./package.json').slug || require('./package.json').name)")

BUMP=""
for a in "$@"; do
  case "$a" in
    --bump)
      shift
      BUMP="${1:-patch}"
      shift || true
      ;;
    --bump=*)
      BUMP="${a#--bump=}"
      shift
      ;;
  esac
done

if [ -n "$BUMP" ]; then
  NEXT=$(node -e "
    const [maj, min, pat] = process.argv[1].split('.').map(n => parseInt(n, 10));
    const b = process.argv[2];
    let out;
    if (b === 'major') out = (maj + 1) + '.0.0';
    else if (b === 'minor') out = maj + '.' + (min + 1) + '.0';
    else out = maj + '.' + min + '.' + (pat + 1);
    console.log(out);
  " "$CUR_VERSION" "$BUMP")
  echo "release.sh: bumping $CUR_VERSION -> $NEXT ($BUMP)"
  node -e "
    const fs = require('fs');
    const p = JSON.parse(fs.readFileSync('package.json', 'utf8'));
    p.version = process.argv[1];
    fs.writeFileSync('package.json', JSON.stringify(p, null, 2) + '\n');
  " "$NEXT"
  CUR_VERSION="$NEXT"
fi

# Optional build step.
if [ -x ./build.sh ]; then
  echo "release.sh: running build.sh"
  ./build.sh
fi

# Publish.
echo "release.sh: publishing $SLUG@$CUR_VERSION to $REGISTRY"
adompkg publish .

# Print published URL.
echo
echo "Published: $REGISTRY/pages/$SLUG"
echo "Install:   adompkg install $SLUG"