#!/usr/bin/env bash
set -e # Exit immediately if a command exits with a non-zero status.

# --- Configuration ---
COMPOSE_FILE="./docker/compose.yml"
DEFAULT_PROJECT_NAME="techtracker"
DEV_PROJECT_NAME="dev-techtracker" # The project name for dev mode

COMPOSE_PROJECT_FLAG=${DEFAULT_PROJECT_NAME} # This will hold "-p dev-techtracker" if --dev is used

# --- Function to display usage ---
usage() {
  echo "Usage: $0 [OPTIONS]"
  echo "Or:    ./update.sh [OPTIONS]" # Assuming the script is named update.sh
  echo ""
  echo "Options:"
  echo "  -d, --dev    Run in development mode, using project name '${DEV_PROJECT_NAME}'."
  echo "               Adds '-p ${DEV_PROJECT_NAME}' to docker compose commands."
  echo "  -h, --help   Display this help message."
  exit 1
}

# --- Parse arguments ---
while [[ "$#" -gt 0 ]]; do
  case "$1" in
    -d|--dev)
      COMPOSE_PROJECT_FLAG=${DEV_PROJECT_NAME}
      shift # Consume the argument
      ;;
    -h|--help)
      usage
      ;;
    *)
      echo "Error: Unknown argument '$1'" >&2
      usage
      ;;
  esac
done

# --- Main Script Logic ---
echo "\n--- Pulling latest git changes ---\n"
git pull
echo "\n--- Building Docker Compose services ${COMPOSE_PROJECT_FLAG} ---\n"
sudo docker compose -p ${COMPOSE_PROJECT_FLAG} -f "${COMPOSE_FILE}" build
echo "\n--- Bringing down Docker Compose services ${COMPOSE_PROJECT_FLAG} ---\n"
sudo docker compose -p ${COMPOSE_PROJECT_FLAG} -f "${COMPOSE_FILE}" down
echo "\n--- Bringing up Docker Compose services ${COMPOSE_PROJECT_FLAG} in detached mode ---\n"
sudo docker compose -p ${COMPOSE_PROJECT_FLAG} -f "${COMPOSE_FILE}" up -d
echo "\n--- Script finished successfully ---\n"
