#!/bin/bash
#
# HOALedgerIQ_Website Deployment Script
# 
# This script performs a zero-downtime deployment by:
# 1. Pulling latest code from git
# 2. Clearing application cache
# 3. Restarting the service
#
# Usage: ./deploy.sh [environment]
# Example: ./deploy.sh production
#

set -e

# =============================================================================
# CONFIGURABLE VARIABLES - Edit these for your server setup
# =============================================================================

# Git configuration
GIT_REMOTE="${GIT_REMOTE:-origin}"
GIT_BRANCH="${GIT_BRANCH:-main}"
GIT_REPO_URL=https://git.sensetostyle.com/JoeBot/HOALedgerIQ_Website.git

# Deployment directory (where the app lives)
DEPLOY_DIR="${DEPLOY_DIR:-/home/ubuntu/www}"

# Service name (the Debian service that wraps your app)
SERVICE_NAME="${SERVICE_NAME:-hoaledgeriqweb}"

# Cache clearing command (adjust based on your framework)
# Examples:
#   - Laravel: php artisan cache:clear && php artisan config:clear && php artisan view:clear
#   - Django: python manage.py clear_cache
#   - Generic: rm -rf cache/* || true
CACHE_CLEAR_CMD="${CACHE_CLEAR_CMD:-rm -rf ${DEPLOY_DIR}/cache/* || true}"

# Git repository URL (for initial clone or if remote needs reset)
GIT_REPO_URL="${GIT_REPO_URL:-}"

# =============================================================================
# DEPLOYMENT LOGIC
# =============================================================================

log() {
    echo "[$(date '+%Y-%m-%d %H:%M:%S')] $1"
}

error() {
    echo "[$(date '+%Y-%m-%d %H:%M:%S')] ERROR: $1" >&2
    exit 1
}

# Check if running as correct user
if [ "$(id -un)" != "ubuntu" ]; then
    error "This script should be run as 'ubuntu' user"
fi

# Navigate to deployment directory
log "Navigating to deployment directory: ${DEPLOY_DIR}"
if [ ! -d "${DEPLOY_DIR}" ]; then
    error "Deployment directory does not exist: ${DEPLOY_DIR}"
fi
cd "${DEPLOY_DIR}"

# Verify git repository exists
if [ ! -d ".git" ]; then
    error "Not a git repository. Please clone the repository first."
fi

# Pull latest code
log "Pulling latest code from ${GIT_REMOTE}/${GIT_BRANCH}"
git fetch "${GIT_REMOTE}" "${GIT_BRANCH}"
git reset --hard "${GIT_REMOTE}/${GIT_BRANCH}"

# Clear cache
log "Clearing application cache"
eval "${CACHE_CLEAR_CMD}"

# Restart service
log "Restarting service: ${SERVICE_NAME}"
if ! systemctl is-active --quiet "${SERVICE_NAME}"; then
    log "Service ${SERVICE_NAME} is not running, attempting to start it"
fi
sudo systemctl restart "${SERVICE_NAME}"

# Verify service is running
sleep 2
if systemctl is-active --quiet "${SERVICE_NAME}"; then
    log "✅ Deployment successful! Service ${SERVICE_NAME} is running."
else
    error "❌ Service ${SERVICE_NAME} failed to start. Check journalctl -u ${SERVICE_NAME} for details."
fi

log "Deployment completed at $(date)"
