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

# CI step: deploy to production via rsync
# Called from .gitea/workflows/deploy.yml
# Required env: RSYNC_USER, RSYNC_PASS, BRANCH

# Read .env
set -o allexport
. ./.env
. ./api/config.yml.env
set +o allexport

# Validate required env vars
for var in RSYNC_USER RSYNC_PASS RSYNC_HOST RSYNC_PORT; do
    if [ -z "${!var:-}" ]; then
        echo "${var} missing, exiting"
        exit 1
    fi
done

echo "Deploying ${BRANCH} to ${RSYNC_HOST} on port ${RSYNC_PORT} as ${RSYNC_USER}"

# Exclude source and sourcemaps on master deploy
excludes=""
if [ "${BRANCH}" = "master" ]; then
    excludes='--exclude=src --exclude=*.map'
    echo "master deploy, excluding ${excludes}"
fi

SSH_CMD="sshpass -p ${RSYNC_PASS} ssh -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no -p ${RSYNC_PORT} -l ${RSYNC_USER}"

# Sync frontend
rsync -rlcgD --perms -i -u -v --stats --progress \
    --delete \
    -e "${SSH_CMD}" \
    ${excludes} \
    frontend/ \
    "${RSYNC_HOST}":./frontend/

# Sync API config and hooks
rsync -rlcgD --perms -i -u -v --stats --progress \
    --delete \
    -e "${SSH_CMD}" \
    api/ \
    "${RSYNC_HOST}":./api/

# Ensure media directory exists on remote
mkdir -p media
chmod 770 media
rsync -rlcgD --perms -i -u -v --stats --progress \
    -e "${SSH_CMD}" \
    media \
    "${RSYNC_HOST}":./

# Reload tibi-server config
reloadUrl="${LIVE_URL}/api/_/admin/reload"
curl -X POST -H "Content-Type: application/json" -H "Authorization: Bearer ${ADMIN_TOKEN}" -d '{}' "${reloadUrl}"

# Clear SSR cache
ssrUrl="${LIVE_URL}/api/ssr"
curl -X POST -H "Content-Type: application/json" -d '{}' "${ssrUrl}?clear=1"
