#!/bin/bash
# A universal deployment script that can be run from a local machine or directly on the server.
#
# - When run locally, it will SSH to the server and execute the deployment.
# - When run on the server, it will execute the deployment directly.

set -e

# --- Configuration ---
REMOTE_USER="jimmyg"
REMOTE_HOST="server1"
REMOTE_DIR="/home/jimmyg/mold_cost_online_tool"
SERVER_HOSTNAME="server1" # The hostname of the production server

# --- Deployment Logic ---
deploy_commands() {
    echo ">>> [1/4] Navigating to the application directory..."
    cd "$REMOTE_DIR"

    echo ">>> [2/4] Pulling latest changes from Git..."
    git pull

    echo ">>> [3/4] Building new container image with the latest code..."
    podman-compose build

    echo ">>> [4/4] Restarting services with the updated image..."
    podman-compose down
    podman-compose up -d

    echo ""
    echo "✅ Deployment finished successfully on $REMOTE_HOST!"
}

# --- Execution ---
# Get the hostname of the machine this script is running on
current_hostname=$(hostname)

if [ "$current_hostname" == "$SERVER_HOSTNAME" ]; then
    echo "🚀 Running deployment script directly on the server ($current_hostname)..."
    deploy_commands
else
    echo "🚀 Running deployment script from local machine ($current_hostname)..."
    echo "Connecting to $REMOTE_USER@$REMOTE_HOST..."
    # Using 'bash -s' allows us to execute the function on the remote server.
    # We pass the function definition and then call it.
    ssh "$REMOTE_USER@$REMOTE_HOST" "$(declare -f deploy_commands); deploy_commands"
fi 