#!/bin/bash

# Set strict error handling
set -e  # Exit immediately if a command exits with a non-zero status
set -u  # Treat unset variables as an error

# Script variables
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"

# Function for logging
log() {
   local timestamp=$(date +"%Y-%m-%d %H:%M:%S")
   echo "[$timestamp] $1"
}

# Function for cleanup on exit
cleanup() {
   log "Cleaning up..."
   # Add cleanup tasks here


   log "Cleanup completed - Deployment Completed."
}

# Register the cleanup function to be called on exit
trap cleanup EXIT

# Main function
main() {
   log "Starting deployment..."

   log "Updating repository to match remote main branch..."
   git fetch origin
   git reset --hard origin/main
   if [ $? -ne 0 ]; then
      log "Failed to update to the latest main branch."
      exit 1
   fi
   log "Repository successfully updated to latest main branch."

   # Lancer le docker
   log "Building and starting Docker containers..."
   docker compose -f "$SCRIPT_DIR/docker-compose.yml" up -d --build
   if [ $? -ne 0 ]; then
      log "Failed to start Docker containers."
      exit 1
   fi
   log "Docker containers started successfully."
   log "Deployment completed successfully."
}

# Execute main function
main "$@"