#!/usr/bin/env bash
#
# Update the @flowdrop/flowdrop package and rebuild the library.
#
# Usage: ./scripts/update-flowdrop.sh <version>
#   e.g. ./scripts/update-flowdrop.sh 0.0.60

set -euo pipefail

VERSION="${1:-}"

if [ -z "$VERSION" ]; then
  echo "Usage: $0 <version>"
  echo "  e.g. $0 0.0.60"
  exit 1
fi

# Resolve paths relative to this script's location (modules/flowdrop_ui_components/)
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
MODULE_DIR="$(cd "$SCRIPT_DIR/.." && pwd)"
LIB_DIR="$MODULE_DIR/lib/flowdrop"
LIBRARIES_YML="$MODULE_DIR/flowdrop_ui_components.libraries.yml"

echo "==> Updating @flowdrop/flowdrop to ^$VERSION"

cd "$LIB_DIR"

echo "==> Installing dependencies (npm install)"
npm install

echo "==> Installing @flowdrop/flowdrop@^$VERSION"
npm install -D "@flowdrop/flowdrop@^$VERSION"

echo "==> Building library (npm run build)"
npm run build

echo "==> Restoring build/.gitignore and build/README.md"
git checkout -- "$LIB_DIR/build/.gitignore" "$LIB_DIR/build/README.md" 2>/dev/null || true

echo "==> Updating version in $LIBRARIES_YML"
sed -i '' -E '/^flowdrop:/{n;s/^(  version: ).*/\1'"$VERSION"'/;}' "$LIBRARIES_YML"

echo "==> Updating version in $LIB_DIR/package.json"
PACKAGE_JSON="$LIB_DIR/package.json"
node -e "
  const fs = require('fs');
  const pkg = JSON.parse(fs.readFileSync('$PACKAGE_JSON', 'utf8'));
  pkg.version = '$VERSION';
  fs.writeFileSync('$PACKAGE_JSON', JSON.stringify(pkg, null, '\t') + '\n');
"

echo "==> Done! @flowdrop/flowdrop updated to $VERSION"
echo "    Remember to clear Drupal caches: ddev drush cr"
