#!/bin/bash

set -e
set -o pipefail


# Parse arguments

UPDATE=false

while [[ $# -gt 0 ]]; do
    case $1 in
        --update)
            UPDATE=true
            shift
            ;;
        -h|--help)
            echo "Usage: $0 [--update]"
            echo ""
            echo "Initialize Wild Cloud scaffold and basic configuration."
            echo ""
            echo "Options:"
            echo "  --update            Update existing cloud files (overwrite)"
            echo "  -h, --help          Show this help message"
            echo ""
            echo "This script will:"
            echo "  - Initialize the .wildcloud directory structure"
            echo "  - Copy template files to the current directory"
            echo "  - Configure basic settings (email, domains, cluster name)"
            echo ""
            echo "After running this script, use:"
            echo "  - wild-setup-cluster   # Set up Kubernetes cluster (Phases 1-3)"
            echo "  - wild-setup-services  # Install cluster services (Phase 4)"
            exit 0
            ;;
        -*)
            echo "Unknown option $1"
            echo "Usage: $0 [--update]"
            echo "Use --help for full usage information"
            exit 1
            ;;
        *)
            echo "Unexpected argument: $1"
            echo "Usage: $0 [--update]"
            echo "Use --help for full usage information"
            exit 1
            ;;
    esac
done

# Initialize Wild Cloud environment
if [ -z "${WC_ROOT}" ]; then
    echo "WC_ROOT is not set."
    exit 1
else
    source "${WC_ROOT}/scripts/common.sh"
fi


# Initialize .wildcloud directory if it doesn't exist.
if [ ! -d ".wildcloud" ]; then
    mkdir -p ".wildcloud"
    UPDATE=true
    echo "Created '.wildcloud' directory."
fi

# =============================================================================
# BASIC CONFIGURATION
# =============================================================================

prompt_if_unset_config "operator.email" "Your email address" ""
prompt_if_unset_config "cloud.baseDomain" "Your base domain name (e.g., example.com)" ""
base_domain=$(wild-config "cloud.baseDomain")
prompt_if_unset_config "cloud.domain" "Your public cloud domain" "cloud.${base_domain}"
domain=$(wild-config "cloud.domain")
prompt_if_unset_config "cloud.internalDomain" "Your internal cloud domain" "internal.${domain}"
prompt_if_unset_config "cloud.backup.root" "Existing path to save backups to" ""

# Derive cluster name from domain if not already set
current_cluster_name=$(wild-config "cluster.name")
if [ -z "$current_cluster_name" ] || [ "$current_cluster_name" = "null" ]; then
    cluster_name=$(echo "${domain}" | tr '.' '-' | tr '[:upper:]' '[:lower:]')
    wild-config-set "cluster.name" "${cluster_name}"
    print_info "Set cluster name to: ${cluster_name}"
fi

# Check if current directory is empty for new cloud
if [ "${UPDATE}" = false ]; then
    # Check if directory has any files (including hidden files, excluding . and .. and .git)
    if [ -n "$(find . -maxdepth 1 -name ".*" -o -name "*" | grep -v "^\.$" | grep -v "^\.\.$" | grep -v "^\./\.git$" | grep -v "^\./\.wildcloud$"| head -1)" ]; then
        echo "Warning: Current directory is not empty."
        read -p "Do you want to overwrite existing files? (y/N): " -n 1 -r
        echo
        if [[ $REPLY =~ ^[Yy]$ ]]; then
            confirm="yes"
        else
            confirm="no"
        fi
        if [ "$confirm" != "yes" ]; then
            echo "Aborting setup. Please run this script in an empty directory."
            exit 1
        fi
    fi
fi

# Copy cloud files to current directory only if they do not exist.
# Ignore files that already exist.
SRC_DIR="${WC_ROOT}/setup/home-scaffold"
rsync -av --ignore-existing --exclude=".git" "${SRC_DIR}/" ./ > /dev/null

print_success "Ready for cluster setup!"

# =============================================================================
# COMPLETION
# =============================================================================

print_header "Wild Cloud Scaffold Setup Complete! Welcome to Wild Cloud!"

echo ""
echo "Next steps:"
echo "  1. Set up your Kubernetes cluster:"
echo "     wild-setup-cluster"
echo ""
echo "  2. Install cluster services:"
echo "     wild-setup-services"
echo ""
echo "Or run the complete setup:"
echo "  wild-setup"

