#!/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"

echo "==> Updating version in $LIBRARIES_YML"
# Replace the version line under the 'flowdrop:' library definition only.
awk -v new_ver="$VERSION" '
  /^flowdrop:/ { in_flowdrop = 1 }
  in_flowdrop && /^  version:/ { $0 = "  version: " new_ver; in_flowdrop = 0 }
  { print }
' "$LIBRARIES_YML" > "$LIBRARIES_YML.tmp" && mv "$LIBRARIES_YML.tmp" "$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"
