#!/bin/bash

set -e # Exit on any error

# Configuration
DOTFILES_DIR="$HOME/dotfiles/orangepi"
TARGET_BASE_DIR="$HOME"
SYSTEMD_DIR="/etc/systemd/system"
USER="orangepi"
GROUP="orangepi"

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# Logging functions
log_info() {
  echo -e "${BLUE}[INFO]${NC} $1"
}

log_success() {
  echo -e "${GREEN}[SUCCESS]${NC} $1"
}

log_warning() {
  echo -e "${YELLOW}[WARNING]${NC} $1"
}

log_error() {
  echo -e "${RED}[ERROR]${NC} $1"
}

# Check if script is run as orangepi user
check_user() {
  if [[ "$USER" != "orangepi" ]]; then
    log_error "This script should be run as the orangepi user"
    exit 1
  fi
}

# Get list of available services
get_available_services() {
  if [[ ! -d "$DOTFILES_DIR" ]]; then
    log_error "Dotfiles directory not found: $DOTFILES_DIR"
    exit 1
  fi

  # Find all directories in dotfiles/orangepi that contain docker-compose.yml
  find "$DOTFILES_DIR" -maxdepth 1 -type d -exec test -f {}/docker-compose.yml \; -print |
    xargs -I {} basename {} | sort
}

# Deploy a single service
deploy_service() {
  local service_name="$1"
  local source_dir="$DOTFILES_DIR/$service_name"
  local target_dir="$TARGET_BASE_DIR/$service_name"

  log_info "Deploying service: $service_name"

  # Check if source directory exists
  if [[ ! -d "$source_dir" ]]; then
    log_error "Source directory not found: $source_dir"
    return 1
  fi

  # Check if docker-compose.yml exists in source
  if [[ ! -f "$source_dir/docker-compose.yml" ]]; then
    log_warning "No docker-compose.yml found in $source_dir, skipping..."
    return 0
  fi

  # Create target directory if it doesn't exist
  if [[ ! -d "$target_dir" ]]; then
    log_info "Creating target directory: $target_dir"
    mkdir -p "$target_dir"
  fi

  # Copy files with rsync (preserves permissions, overwrites existing)
  # No --delete flag = only copy/overwrite, never delete from target
  log_info "Copying files from $source_dir to $target_dir"
  rsync -av "$source_dir/" "$target_dir/"

  # Fix ownership
  log_info "Setting ownership to $USER:$GROUP"
  sudo chown -R "$USER:$GROUP" "$target_dir"

  # Create/update systemd service
  create_systemd_service "$service_name" "$target_dir"

  log_success "Service $service_name deployed successfully"
}

# Create systemd service file
create_systemd_service() {
  local service_name="$1"
  local working_dir="$2"
  local service_file="$SYSTEMD_DIR/${service_name}-docker.service"

  log_info "Creating systemd service: ${service_name}-docker.service"

  # Create systemd service file matching your existing pattern
  sudo tee "$service_file" >/dev/null <<EOF
[Unit]
Description=${service_name^} Docker Compose Application
Requires=docker.service
After=docker.service network-online.target
Wants=network-online.target

[Service]
Type=oneshot
RemainAfterExit=yes
WorkingDirectory=${working_dir}
ExecStart=/usr/bin/docker compose up -d
ExecStop=/usr/bin/docker compose down
TimeoutStartSec=0

[Install]
WantedBy=multi-user.target
EOF

  # Reload systemd and enable service
  sudo systemctl daemon-reload
  sudo systemctl enable "${service_name}-docker.service"

  log_success "Systemd service ${service_name}-docker.service created and enabled"
}

# Show usage
show_usage() {
  echo "Usage: $0 [service1] [service2] ..."
  echo ""
  echo "Deploy homelab services from dotfiles to operational directories"
  echo ""
  echo "Examples:"
  echo "  $0                    # Deploy all available services"
  echo "  $0 media storage      # Deploy only media and storage services"
  echo "  $0 nginx              # Deploy only nginx service"
  echo ""
  echo "Available services:"
  get_available_services | sed 's/^/  /'
}

# Main deployment function
main() {
  log_info "Starting homelab deployment..."

  # Check prerequisites
  check_user

  # Get available services
  available_services=($(get_available_services))

  if [[ ${#available_services[@]} -eq 0 ]]; then
    log_error "No services found in $DOTFILES_DIR"
    exit 1
  fi

  # Determine services to deploy
  if [[ $# -eq 0 ]]; then
    # Deploy all services
    services_to_deploy=("${available_services[@]}")
    log_info "No services specified, deploying all available services"
  else
    # Deploy specified services
    services_to_deploy=("$@")
    log_info "Deploying specified services: ${services_to_deploy[*]}"

    # Validate specified services exist
    for service in "${services_to_deploy[@]}"; do
      if [[ ! " ${available_services[*]} " =~ " ${service} " ]]; then
        log_error "Service '$service' not found in dotfiles"
        log_info "Available services: ${available_services[*]}"
        exit 1
      fi
    done
  fi

  # Deploy each service
  failed_services=()
  for service in "${services_to_deploy[@]}"; do
    if ! deploy_service "$service"; then
      failed_services+=("$service")
    fi
  done

  # Summary
  echo ""
  log_info "Deployment Summary:"
  log_success "Successfully deployed: ${#services_to_deploy[@]} services"

  if [[ ${#failed_services[@]} -gt 0 ]]; then
    log_error "Failed services: ${failed_services[*]}"
    exit 1
  fi

  echo ""
  log_info "Next steps:"
  echo "  • Check service status: sudo systemctl status <service>-docker.service"
  echo "  • Start services: sudo systemctl start <service>-docker.service"
  echo "  • View logs: journalctl -u <service>-docker.service -f"
  echo ""
  log_success "All services deployed successfully! 🚀"
}

# Handle help flag
if [[ "$1" == "-h" || "$1" == "--help" ]]; then
  show_usage
  exit 0
fi

# Run main function
main "$@"
