#!/bin/sh
# update.sh — fix .git ownership then pull latest code (FreeBSD / Apache 2.4)
# Runs as root. Invoked from update-app.php, which runs as the "www" user.
#
# Allow the web user to run this as root without a password via doas.
# Add to /usr/local/etc/doas.conf:
#     permit nopass www as root cmd /var/www/arrisa/update.sh
# Make the script executable:  chmod +x /var/www/arrisa/update.sh
# Have PHP invoke it as:        doas /var/www/arrisa/update.sh
# (sudo equivalent, if you use sudo instead:
#     www ALL=(root) NOPASSWD: /var/www/arrisa/update.sh )

# pkg installs git/php/apachectl under /usr/local; doas/PHP pass a minimal PATH.
export PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
export HOME=/root   # predictable git/ssh config + key lookup when run as root

REPO_DIR="$(cd "$(dirname "$0")" && pwd)"

WEB_USER=www
WEB_GROUP=www

# git refuses to operate on a tree owned by another user ("dubious ownership");
# since we chown .git to www but run as root, scope a safe.directory per call.
git_safe() {
    git -c safe.directory="$REPO_DIR" "$@"
}

# Fix ownership so both the web user and the repo can write to .git
chown -R "${WEB_USER}:${WEB_GROUP}" "$REPO_DIR/.git"
chmod -R g+rwX "$REPO_DIR/.git"

cd "$REPO_DIR" || exit 1

# Discard any local changes to tracked files so pull always succeeds
git_safe reset --hard HEAD 2>&1
git_safe clean -fd 2>&1

# Pull latest code
git_safe pull origin main 2>&1

# Create queue directories and fix permissions
# NOTE: fix-permissions.sh must also be FreeBSD/POSIX-safe (same www + path fixes).
# If it genuinely needs bash, `pkg install bash` and call it with bash instead of sh.
echo "Fixing permissions..."
sh "$REPO_DIR/fix-permissions.sh" 2>&1

# Run any pending database migrations
echo "Running database migrations..."
php "$REPO_DIR/database/run-migrations.php" 2>&1

# Gracefully reload Apache so new code is picked up without dropping live connections
if command -v apachectl >/dev/null 2>&1; then
    apachectl graceful 2>&1
    echo "Apache graceful reload triggered (apachectl graceful)."
elif service apache24 graceful >/dev/null 2>&1; then
    echo "Apache graceful reload triggered (service apache24 graceful)."
eLse
    echo "WARNING: Could not reload Apache. Reload it manually: service apache24 graceful"
fi
