#!/usr/bin/env bash
set -euo pipefail
cd /home/ubuntu/repo/facere-website
before=$(git rev-parse HEAD)
git fetch --quiet origin main
after=$(git rev-parse origin/main)
if [ "$before" = "$after" ]; then
  exit 0
fi

changed=$(git diff --name-only "$before" "$after")
nginx_conf_changed=0
compose_changed=0
hook_changed=0
if grep -qx 'deploy/conf.d/default.conf' <<<"$changed"; then nginx_conf_changed=1; fi
if grep -qx 'deploy/docker-compose.yml'   <<<"$changed"; then compose_changed=1;    fi
if grep -qx 'deploy/hook.py'              <<<"$changed"; then hook_changed=1;       fi

git reset --hard origin/main
echo "[$(date -Is)] deployed $before -> $after"

if [ "$compose_changed" = "1" ]; then
  ( cd /home/ubuntu/repo/facere-website/deploy && sudo -n docker compose up -d ) >/dev/null
  echo "[$(date -Is)] docker compose up -d (compose changed)"
elif [ "$nginx_conf_changed" = "1" ]; then
  if sudo -n docker exec facere-web nginx -t >/dev/null 2>&1; then
    sudo -n docker exec facere-web nginx -s reload >/dev/null
    echo "[$(date -Is)] nginx reloaded (default.conf changed)"
  else
    echo "[$(date -Is)] nginx config test FAILED, not reloading" >&2
  fi
fi

if [ "$hook_changed" = "1" ]; then
  sudo -n systemctl restart facere-deploy-hook >/dev/null || true
  echo "[$(date -Is)] facere-deploy-hook restarted (hook.py changed)"
fi
