#!/bin/bash
# Cariflex EMS - Multi-Environment Deployment Script
# Usage: ./deploy.sh [dev|test|prod] [full|fm|openadr|citrine|grafana]

set -e

ENV="${1:-dev}"
COMPONENT="${2:-full}"
CARIFLEX_HOME="/home/eric/cariflex"
FLEXMEASURES_HOME="/home/eric/flexmeasures"

# Colors
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m'

log() { echo -e "${GREEN}[$(date +'%Y-%m-%d %H:%M:%S')]${NC} $1"; }
warn() { echo -e "${YELLOW}[$(date +'%Y-%m-%d %H:%M:%S')] WARNING:${NC} $1"; }
error() { echo -e "${RED}[$(date +'%Y-%m-%d %H:%M-%S')] ERROR:${NC} $1"; exit 1; }

# Environment-specific configuration
case "$ENV" in
  dev)
    FM_DOMAIN="cariflex.dev.local"
    GRAFANA_DOMAIN="grafana.dev.local"
    CITRINEOS_DOMAIN="citrineos.dev.local"
    REPLICAS=1
    DEBUG=true
    LOG_LEVEL="DEBUG"
    ;;
  test)
    FM_DOMAIN="cariflex.test.digitribe.fr"
    GRAFANA_DOMAIN="grafana.test.digitribe.fr"
    CITRINEOS_DOMAIN="citrineos.test.digitribe.fr"
    REPLICAS=1
    DEBUG=false
    LOG_LEVEL="INFO"
    ;;
  prod)
    FM_DOMAIN="cariflex.digitribe.fr"
    GRAFANA_DOMAIN="grafana.digitribe.fr"
    CITRINEOS_DOMAIN="citrineos.digitribe.fr"
    REPLICAS=2
    DEBUG=false
    LOG_LEVEL="WARNING"
    ;;
  *)
    error "Unknown environment: $ENV (use dev, test, or prod)"
    ;;
esac

log "Deploying Cariflex EMS to $ENV environment"
log "Component: $COMPONENT"
log "FM Domain: $FM_DOMAIN"
log "Replicas: $REPLICAS"

# Function to deploy a docker-compose stack
deploy_stack() {
  local compose_file="$1"
  local stack_name="$2"
  
  log "Deploying $stack_name from $compose_file..."
  
  # Generate environment-specific override
  cat > "/tmp/docker-compose.${ENV}.override.yml" << EOF
version: '3.8'
services:
  server:
    environment:
      - LOGGING_LEVEL=${LOG_LEVEL}
      - FLEXMEASURES_ENV=${ENV}
    labels:
      - "traefik.http.routers.${stack_name}.rule=Host(\`${FM_DOMAIN}\`)"
EOF
  
  # Deploy
  docker compose -f "$compose_file" -f "/tmp/docker-compose.${ENV}.override.yml" up -d
  
  log "$stack_name deployed successfully"
}

# Deploy based on component
case "$COMPONENT" in
  full)
    log "Deploying full stack..."
    deploy_stack "$FLEXMEASURES_HOME/docker-compose.yml" "flexmeasures"
    deploy_stack "$FLEXMEASURES_HOME/docker-compose.openadr.yml" "openadr"
    deploy_stack "$CARIFLEX_HOME/config/docker-compose-citrineos.yml" "citrineos"
    ;;
  fm)
    deploy_stack "$FLEXMEASURES_HOME/docker-compose.yml" "flexmeasures"
    ;;
  openadr)
    deploy_stack "$FLEXMEASURES_HOME/docker-compose.openadr.yml" "openadr"
    ;;
  citrine)
    deploy_stack "$CARIFLEX_HOME/config/docker-compose-citrineos.yml" "citrineos"
    ;;
  *)
    error "Unknown component: $COMPONENT (use full, fm, openadr, citrine)"
    ;;
esac

# Health checks
log "Running health checks..."

check_service() {
  local name="$1"
  local url="$2"
  local max_attempts="${3:-30}"
  
  for i in $(seq 1 $max_attempts); do
    if curl -sk "$url" > /dev/null 2>&1; then
      log "$name is healthy"
      return 0
    fi
    sleep 2
  done
  
  warn "$name health check failed after ${max_attempts} attempts"
  return 1
}

check_service "FlexMeasures" "https://${FM_DOMAIN}/api/v3_0/sensors" 30
check_service "OpenADR VTN" "http://openadr-vtn:8080/OpenADR2/Simple/2.0b" 10
check_service "CitrineOS" "http://cariflex-citrineos-server:8080" 10

# Summary
log "Deployment complete!"
log ""
log "Environment: $ENV"
log "URLs:"
log "  FlexMeasures: https://${FM_DOMAIN}"
log "  Grafana: https://${GRAFANA_DOMAIN}"
log "  CitrineOS: https://${CITRINEOS_DOMAIN}"
log ""
log "Containers:"
docker ps --format "  {{.Names}}: {{.Status}}" | grep -E "flexmeasures|openadr|citrine|grafana"

# Cleanup
rm -f "/tmp/docker-compose.${ENV}.override.yml"
