#!/usr/bin/env bash
# Deploy Iliya theme -> production (iliyafa.com). See DEPLOY.md.
#   ./deploy.sh            build + sync whole theme (php, templates, assets)
#   ./deploy.sh --assets   build + push only dist.css + dist.js (fast, no php change)
set -euo pipefail

KEY=~/.ssh/iliya_deploy
PORT=49150
SRV=iliyafa@185.88.154.85
RDIR=/home/iliyafa/public_html/wp-content/themes/iliya
WPROOT=/home/iliyafa/public_html
HERE="$(cd "$(dirname "$0")" && pwd)"
cd "$HERE"

echo "▶ building…"
npm run build

if [[ "${1:-}" == "--assets" ]]; then
  echo "▶ pushing assets only…"
  scp -i "$KEY" -P "$PORT" assets/css/dist.css "$SRV:$RDIR/assets/css/dist.css"
  scp -i "$KEY" -P "$PORT" assets/js/dist.js  "$SRV:$RDIR/assets/js/dist.js"
else
  echo "▶ packaging theme…"
  tar czf /tmp/iliya-theme.tar.gz \
    --exclude=node_modules --exclude=.git --exclude='*.tar.gz' .
  echo "▶ uploading…"
  scp -i "$KEY" -P "$PORT" /tmp/iliya-theme.tar.gz "$SRV:/home/iliyafa/"
  echo "▶ extracting…"
  ssh -i "$KEY" -p "$PORT" "$SRV" \
    "cd $RDIR && tar xzf ~/iliya-theme.tar.gz && rm -f ~/iliya-theme.tar.gz"
  rm -f /tmp/iliya-theme.tar.gz
fi

echo "▶ flushing cache…"
ssh -i "$KEY" -p "$PORT" "$SRV" "~/bin/wp cache flush --path=$WPROOT" || true

echo "▶ verify:"
for p in / wp-content/themes/iliya/assets/css/dist.css wp-content/themes/iliya/assets/js/dist.js; do
  curl -sS -k -o /dev/null -w "  $p -> %{http_code}\n" "https://iliyafa.com/$p" --max-time 20 || true
done
echo "✓ done"
