#!/bin/bash
#
# AtlasOS - Calypso Appliance Installer
# Complete installation script for Calypso backup appliance
# Target OS: Ubuntu Server 24.04 LTS
#
# Usage: sudo ./installer/alpha/install.sh [options]
#
# Options:
#   --version VERSION    Install specific version (default: auto-detect)
#   --skip-deps          Skip system dependencies installation
#   --skip-zfs           Skip ZFS installation
#   --skip-scst          Skip SCST installation
#   --skip-mhvtl         Skip MHVTL installation
#   --skip-bacula        Skip Bacula installation
#   --config-only        Only setup configuration, don't install binaries
#

set -euo pipefail

# Script directory
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
INSTALLER_DIR="$SCRIPT_DIR"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"

# 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 "${GREEN}[INFO]${NC} $1"
}

log_warn() {
    echo -e "${YELLOW}[WARN]${NC} $1"
}

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

log_step() {
    echo -e "\n${BLUE}==>${NC} $1"
}

# Configuration
CALYPSO_VERSION="${CALYPSO_VERSION:-1.0.0-alpha}"
INSTALL_PREFIX="/opt/adastra/calypso"
CONFIG_DIR="/etc/calypso"
DATA_DIR="/srv/calypso"
LOG_DIR="/var/log/calypso"
LIB_DIR="/var/lib/calypso"
RUN_DIR="/run/calypso"

# Flags
SKIP_DEPS=false
SKIP_ZFS=false
SKIP_SCST=false
SKIP_MHVTL=false
SKIP_BACULA=false
CONFIG_ONLY=false

# Parse arguments
while [[ $# -gt 0 ]]; do
    case $1 in
        --version)
            CALYPSO_VERSION="$2"
            shift 2
            ;;
        --skip-deps)
            SKIP_DEPS=true
            shift
            ;;
        --skip-zfs)
            SKIP_ZFS=true
            shift
            ;;
        --skip-scst)
            SKIP_SCST=true
            shift
            ;;
        --skip-mhvtl)
            SKIP_MHVTL=true
            shift
            ;;
        --skip-bacula)
            SKIP_BACULA=true
            shift
            ;;
        --config-only)
            CONFIG_ONLY=true
            shift
            ;;
        *)
            log_error "Unknown option: $1"
            exit 1
            ;;
    esac
done

# Check if running as root
if [[ $EUID -ne 0 ]]; then
    log_error "This script must be run as root (use sudo)"
    exit 1
fi

# Detect OS
if ! grep -q "Ubuntu" /etc/os-release 2>/dev/null; then
    log_warn "This installer is designed for Ubuntu. Proceeding anyway..."
fi

log_info "=========================================="
log_info "AtlasOS - Calypso Appliance Installer"
log_info "Version: ${CALYPSO_VERSION}"
log_info "=========================================="
log_info ""

# Source helper scripts
source "$INSTALLER_DIR/scripts/helpers.sh"
source "$INSTALLER_DIR/scripts/filesystem.sh"
source "$INSTALLER_DIR/scripts/dependencies.sh"
source "$INSTALLER_DIR/scripts/components.sh"
source "$INSTALLER_DIR/scripts/application.sh"
source "$INSTALLER_DIR/scripts/database.sh"
source "$INSTALLER_DIR/scripts/services.sh"
source "$INSTALLER_DIR/scripts/configuration.sh"
source "$INSTALLER_DIR/scripts/configure-services.sh"
source "$INSTALLER_DIR/scripts/post-install.sh"

# Main installation function
main() {
    log_step "Starting Calypso Appliance Installation"
    
    # Pre-flight checks
    log_step "Pre-flight Checks"
    check_prerequisites
    
    # Create filesystem structure
    log_step "Creating Filesystem Structure"
    create_filesystem_structure
    
    # Install system dependencies
    if [[ "$SKIP_DEPS" == "false" ]]; then
        log_step "Installing System Dependencies"
        install_system_dependencies
    else
        log_info "Skipping system dependencies installation"
    fi
    
    # Install components
    if [[ "$SKIP_ZFS" == "false" ]]; then
        log_step "Installing ZFS"
        install_zfs || log_warn "ZFS installation failed or already installed"
    fi
    
    if [[ "$SKIP_SCST" == "false" ]]; then
        log_step "Installing SCST"
        install_scst || log_warn "SCST installation failed or already installed"
    fi
    
    if [[ "$SKIP_MHVTL" == "false" ]]; then
        log_step "Installing MHVTL"
        install_mhvtl || log_warn "MHVTL installation failed or already installed"
    fi
    
    if [[ "$SKIP_BACULA" == "false" ]]; then
        log_step "Installing Bacula (Optional)"
        install_bacula || log_warn "Bacula installation skipped or failed"
    fi
    
    # File sharing services are installed in dependencies step
    # ClamAV is installed in dependencies step
    
    # Build and install application
    if [[ "$CONFIG_ONLY" == "false" ]]; then
        log_step "Building and Installing Application"
        build_and_install_application
    else
        log_info "Skipping application build (config-only mode)"
    fi
    
    # Setup database
    log_step "Setting Up Database"
    setup_database
    
    # Setup configuration
    log_step "Setting Up Configuration"
    setup_configuration
    
    # Install systemd services
    log_step "Installing Systemd Services"
    install_systemd_services
    
    # Configure file sharing and antivirus services
    log_step "Configuring File Sharing and Antivirus Services"
    configure_all_services
    
    # Final verification
    log_step "Verifying Installation"
    verify_installation
    
    # Post-installation setup
    log_step "Post-Installation Setup"
    post_install_setup
    
    # Print summary
    print_installation_summary
}

# Run main installation
main

log_info ""
log_info "=========================================="
log_info "Installation Complete!"
log_info "=========================================="
log_info ""
log_info "Next steps:"
log_info "1. Configure /etc/calypso/config.yaml"
log_info "2. Set environment variables in /etc/calypso/secrets.env"
log_info "3. Start services: sudo systemctl start calypso-api"
log_info "4. Access web UI: http://<server-ip>:3000"
log_info "5. Login with default admin credentials (check above)"
log_info ""

