#!/usr/bin/env bash
set -e
BRANCH="main"
GIT_DIR="/var/www/html/hvpulse/hvpulse.git"
TARGET="/var/www/html/hvpulse"
PHP="$(command -v php || echo /usr/bin/php)"
COMPOSER="$(command -v composer || echo /usr/bin/composer)"

read oldrev newrev ref
if [ "$ref" = "refs/heads/$BRANCH" ]; then
  echo "Deploying $BRANCH to $TARGET..."
  git --work-tree="$TARGET" --git-dir="$GIT_DIR" checkout -f "$BRANCH"
  cd "$TARGET"
  $COMPOSER install --no-dev --prefer-dist --no-interaction --no-progress
  $PHP artisan migrate --force || true
  $PHP artisan config:cache
  $PHP artisan route:cache
  $PHP artisan view:cache
  chown -R mycloud:www-data storage bootstrap/cache
  find storage -type d -exec chmod 775 {} \; || true
  find storage -type f -exec chmod 664 {} \; || true
  chmod -R 775 bootstrap/cache
  echo "✅ Deploy complete."
fi
