#!/bin/bash

set -eo pipefail # Exit on error, treat unset variables as an error, and propagate pipeline errors

APP_DIR="/virt/nexus-timer"
IMAGE_NAME="virt-nexus-timer"
SERVICE_NAME="virt-nexus-timer.service"
LOG_FILE="/var/log/webhook-redeploy-nexus-timer.log" # Optional: for script-specific logging

# Redirect stdout and stderr to a log file and also to the console (for webhook response)
exec > >(tee -a "$LOG_FILE") 2>&1

echo "----------------------------------------------------"
echo "Webhook redeploy-nexus-timer triggered at $(date)"
echo "Branch/Ref: $1"
echo "Repository: $2"
echo "----------------------------------------------------"

# Ensure script is run from the app directory
cd "$APP_DIR" || { echo "ERROR: Failed to cd to $APP_DIR. Exiting."; exit 1; }

# Optional: Check if the trigger is for the correct branch (e.g., main or master)
# TARGET_BRANCH="refs/heads/main" # Adjust to your primary branch name
# if [ "$1" != "$TARGET_BRANCH" ]; then
#   echo "Webhook triggered for branch $1, but only deploying $TARGET_BRANCH. Exiting."
#   exit 0 # Exit successfully to not show an error in Gitea for non-target branches
# fi

echo "Pulling latest changes from Git (main branch)..."
# Ensure you are on the correct branch first or specify it in the pull
# git checkout main # Uncomment if your repo might be on other branches
git pull --rebase origin main || { echo "ERROR: git pull failed. Exiting."; exit 1; } # Adjust 'main' if needed

echo "Building Docker image $IMAGE_NAME..."
docker build -t "$IMAGE_NAME" . || { echo "ERROR: docker build failed. Exiting."; exit 1; }

echo "Restarting systemd service $SERVICE_NAME..."
# This command might require sudo privileges. See note below.
sudo systemctl restart "$SERVICE_NAME" || { echo "ERROR: systemctl restart failed. Exiting."; exit 1; }

echo "Deployment finished successfully at $(date)."
echo "----------------------------------------------------"

exit 0