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

VPS_KEY="/Volumes/MDI OTG Drive/Accounts/Accurate CarWash/vps/cloudeagent"
VPS_USER="mypro26"
VPS_HOST="vps73653.inmotionhosting.com"
VPS_PATH="/home/mypro26/public_html/service.mypropertysos.com"
PHP="/opt/cpanel/ea-php84/root/usr/bin/php"
COMPOSER="/home/mypro26/bin/composer"

echo "▶ Building frontend assets…"
pnpm build

echo "▶ Syncing files to VPS…"
rsync -az --progress \
  --exclude='.git' \
  --exclude='.env' \
  --exclude='public/hot' \
  --exclude='public/storage' \
  --exclude='node_modules' \
  --exclude='storage/logs' \
  --exclude='storage/framework/cache' \
  --exclude='storage/framework/sessions' \
  --exclude='storage/framework/views' \
  --exclude='storage/app/public' \
  --exclude='storage/app/auth-appearance.json' \
  -e "ssh -i '${VPS_KEY}'" \
  ./ \
  "${VPS_USER}@${VPS_HOST}:${VPS_PATH}/"

echo "▶ Running post-deploy steps on VPS…"
ssh -i "${VPS_KEY}" "${VPS_USER}@${VPS_HOST}" bash <<REMOTE
  set -e
  cd ${VPS_PATH}

  rm -f public/hot

  echo "  composer install…"
  ${PHP} ${COMPOSER} install --no-dev --optimize-autoloader --no-interaction --quiet

  echo "  storage:link…"
  ${PHP} artisan storage:link --force
  chmod 755 storage/app/public/car-wash-icons 2>/dev/null || true

  echo "  caches…"
  ${PHP} artisan config:cache
  ${PHP} artisan route:cache
  ${PHP} artisan view:cache

  echo "  migrate…"
  ${PHP} artisan migrate --force

  echo "  Done."
REMOTE

echo "✓ Deployed to https://service.mypropertysos.com"
