#!/bin/sh
set -e

# Деплой EN: git sync → cp src+public → install → build → pm2 restart
REPO_DIR="${REPO_DIR:-$HOME/ICA_Events}"
PUBLIC_DIR="${PUBLIC_DIR:-$HOME/public_html}"
PM2_NAME="${PM2_NAME:-ICA Events}"
PORT="${PORT:-3000}"

cd "$REPO_DIR"

if [ -d .git/rebase-merge ] || [ -d .git/rebase-apply ]; then
  git rebase --abort || true
fi

if [ -f .git/MERGE_HEAD ]; then
  git merge --abort || true
fi

echo "Syncing with origin/main..."
git fetch origin
git reset --hard origin/main
git clean -fd

if [ -f scripts/install-git-hooks.sh ]; then
  sh scripts/install-git-hooks.sh
fi

echo "Copying src and public to public_html..."
sudo cp -Rf src/ "$PUBLIC_DIR/src/"
sudo cp -Rf public/ "$PUBLIC_DIR/public/"

cd "$PUBLIC_DIR"

echo "Installing dependencies..."
yarn install
sh "$REPO_DIR/scripts/fix-node-permissions.sh"

echo "Building..."
yarn build

echo "Restarting PM2: $PM2_NAME"
pm2 delete "$PM2_NAME" 2>/dev/null || true
pm2 start yarn --name "$PM2_NAME" -- start --port "$PORT"

echo "Deploy complete."
pm2 status
