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

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

RESET=false
SAFARI=false

usage() {
  cat <<EOF
Usage: $(basename "$0") [--reset] [--safari]

Options:
  --reset     Remove node_modules before installing dependencies (full reset)
  --safari    Perform the Safari step: run build-safari, rename .safari.js files, and copy to BBB
  --help      Show this help message
EOF
}

# Parse arguments
for var in "$@"; do
  case "$var" in
    --reset) RESET=true ;;
    --safari) SAFARI=true ;;
    --help|-h) usage; exit 0 ;;
    *) echo "Unknown option: $var"; usage; exit 2 ;;
  esac
done

if $RESET; then
  echo "Performing a full reset..."
  rm -rf node_modules
fi

# Install missing dependencies if needed
if [ ! -d ./node_modules ] || ! npm ls --depth=0 >/dev/null 2>&1; then
  echo "Running npm install..."
  npm ci --no-progress
fi

# Build
rm -rf dist

if $SAFARI; then
  echo "Running Safari build..."
  npm run build-safari
  echo "Running regular build..."
  npm run build
else
  echo "Running regular build (Safari step skipped)..."
  npm run build
fi

# Safari-specific steps
if $SAFARI; then
  cd dist

  # Extract hash from bundle.*.js generated by the regular build
  HASH="$(ls -1 | grep -Eo 'bundle\.[a-f0-9]{20}\.js' | head -n 1 | grep -Eo '[a-f0-9]{20}' || true)"
  if [ -z "${HASH:-}" ]; then
    echo "Bundle hash not found. Skipping Safari file renaming."
  else
    shopt -s nullglob
    for FILE in *.safari.js *.safari.js.map; do
      # Skip if file already contains the hash
      if [[ "$FILE" == *".$HASH."* ]]; then
        continue
      fi

      PREFIX="${FILE%%.safari.js*}"
      SUFFIX="${FILE#*.safari.js}"     # ".js" or ".js.map"
      NEW_NAME="${PREFIX}.${HASH}.safari.js${SUFFIX}"

      echo "Renaming $FILE → $NEW_NAME"
      mv -- "$FILE" "$NEW_NAME"
    done
    shopt -u nullglob
  fi

  cd ..
fi

echo "Copying dist/* to /usr/share/bigbluebutton/html5-client/..."
sudo cp -rf dist/* /usr/share/bigbluebutton/html5-client/

echo "Switching nginx config to static and restarting nginx..."
sudo ln -sf /usr/share/bigbluebutton/nginx/bbb-html5.nginx.static /usr/share/bigbluebutton/nginx/bbb-html5.nginx
sudo systemctl restart nginx

echo -e '\n\n----------------\nbbb-html5 updated'
