#!/usr/bin/env bash
# Sync git clone -> live public_html copy (when two folders exist on cPanel)
set -euo pipefail

SOURCE="${SOURCE:-/home/duiclick/test.duiclick.com}"
TARGET="${TARGET:-/home/duiclick/public_html/test.duiclick.com}"
PHP_BIN="${PHP_BIN:-/usr/local/bin/php}"

if [[ ! -d "${SOURCE}/.git" ]]; then
  echo "ERROR: Git source not found: ${SOURCE}"
  exit 1
fi

if [[ ! -d "${TARGET}" ]]; then
  echo "ERROR: Live target not found: ${TARGET}"
  exit 1
fi

echo "== Sync ${SOURCE} -> ${TARGET} =="

sync_with_rsync() {
  rsync -av \
    --exclude '.git' \
    --exclude '.env' \
    --exclude 'storage/logs/' \
    --exclude 'storage/framework/sessions/' \
    --exclude 'storage/framework/cache/data/' \
    "${SOURCE}/" "${TARGET}/"
}

sync_with_tar() {
  echo "rsync not found — using tar copy instead."
  tar -C "${SOURCE}" \
    --exclude='.git' \
    --exclude='.env' \
    --exclude='./storage/logs' \
    --exclude='./storage/framework/sessions' \
    --exclude='./storage/framework/cache/data' \
    -cf - . | tar -C "${TARGET}" -xf -
}

if command -v rsync >/dev/null 2>&1; then
  sync_with_rsync
else
  sync_with_tar
fi

cd "${TARGET}"
export PHP_BIN
/bin/bash scripts/deploy/cpanel-post-deploy.sh

echo "== Sync complete. Reset OPcache in cPanel, then Ctrl+F5 in browser. =="
