#!/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

# Detect whether the bind-mounted nginx.conf changed in this update.
# Docker bind-mounts the file by inode, so a `git reset` (which replaces
# the file) requires a container restart for the new config to take effect.
nginx_changed=0
if git diff --name-only "$before" "$after" | grep -qx 'deploy/nginx.conf'; then
  nginx_changed=1
fi

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

if [ "$nginx_changed" = "1" ]; then
  sudo -n docker restart facere-web >/dev/null
  echo "[$(date -Is)] restarted facere-web (nginx.conf changed)"
fi
