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

REMOTE="${REMOTE:-klcbot@klcweb.com}"
REMOTE_DIR="${REMOTE_DIR:-/home/klcbot/bot.klcweb.com}"
ssh_command=(ssh -o BatchMode=yes)

paths=(
  ".htaccess"
  "api"
  "src"
  "ui"
  "scripts"
)

if [[ -e "robot_control.php" ]]; then
  paths+=("robot_control.php")
fi

existing_paths=()
for path in "${paths[@]}"; do
  if [[ -e "$path" ]]; then
    existing_paths+=("$path")
  fi
done

if [[ ${#existing_paths[@]} -eq 0 ]]; then
  echo "No deployable files found."
  exit 1
fi

echo "Checking ${REMOTE}:${REMOTE_DIR}"
"${ssh_command[@]}" "$REMOTE" "mkdir -p '$REMOTE_DIR'"

changes="$(
  rsync -azcR --dry-run --itemize-changes \
    --chmod=D777,F777 \
    -e "${ssh_command[*]}" \
    "${existing_paths[@]}" \
    "${REMOTE}:${REMOTE_DIR}/"
)"

if [[ -z "$changes" ]]; then
  echo "Server is already in sync."
  exit 0
fi

echo "Changes found:"
echo "$changes"
echo "Syncing live server..."

rsync -azcR --itemize-changes \
  --chmod=D777,F777 \
  -e "${ssh_command[*]}" \
  "${existing_paths[@]}" \
  "${REMOTE}:${REMOTE_DIR}/"

"${ssh_command[@]}" "$REMOTE" "chmod -R 777 '$REMOTE_DIR'"
echo "Sync complete."
