#!/bin/bash

# --- Configuration ---
SOURCE_DIR="/mnt/ssd_data/html/early_access/"
BACKUP_PARENT_DIR="/mnt/ssd_data/my_sport_manager_backups/"
HTML_PARENT="/mnt/ssd_data/html/"
LOG_FILE="${BACKUP_PARENT_DIR}deploy_history.log"

# Global variable for selection
SELECTED_VERSION_PATH=""

# --- Logging Function ---
log_message() {
    local type="$1"
    local message="$2"
    local timestamp=$(date "+%Y-%m-%d %H:%M:%S")
    local log_entry="[$timestamp] [$type] $message"
    
    # Write to terminal
    if [[ "$type" == "ERROR" ]]; then
        echo -e "❌ $message" >&2
    elif [[ "$type" == "SUCCESS" ]]; then
        echo -e "✅ $message"
    else
        echo -e "ℹ️ $message"
    fi

    # Append to log file (ensure directory exists first)
    mkdir -p "$(dirname "$LOG_FILE")"
    echo "$log_entry" >> "$LOG_FILE"
}

# --- Environment Checks ---
check_mounts() {
    if ! mountpoint -q "/mnt/ssd_data"; then
        log_message "ERROR" "Drive 'ssd_data' is not mounted. Exiting."
        exit 1
    fi
    if [ ! -d "$BACKUP_PARENT_DIR" ]; then
        log_message "INFO" "Creating backup directory: $BACKUP_PARENT_DIR"
        mkdir -p "$BACKUP_PARENT_DIR"
    fi
}

# --- Core Engine ---
perform_rsync() {
    local src="$1"
    local dst="$2"
    local message="$3"
    local mode="$4"

    # Ensure source ends with / to copy contents, not the folder itself
    [[ "$src" != */ ]] && src="$src/"
    
    log_message "INFO" "$message $dst..."

    local args=("-ah" "--info=progress2")
    [[ "$mode" == "revert" ]] && args+=("--delete-before")

    if sudo rsync "${args[@]}" "$src" "$dst"; then
        log_message "SUCCESS" "Rsync completed: $src -> $dst"
    else
        log_message "ERROR" "Rsync failed during: $message"
        exit 1
    fi
}

# --- Version Selector ---
select_version_dir() {
    local prompt_message="$1"
    local num_to_show=5
    local show_full_list=false
    SELECTED_VERSION_PATH=""

    # Use globbing to avoid 'ls' parsing issues
    local versions=()
    shopt -s nullglob
    for d in "${BACKUP_PARENT_DIR}"MySportManager*/; do
        versions+=("$(basename "$d")")
    done
    shopt -u nullglob

    # Sort versions descending (newest first)
    IFS=$'\n' versions=($(sort -r <<<"${versions[*]}"))
    unset IFS

    if [ ${#versions[@]} -eq 0 ]; then
        log_message "ERROR" "No backups found in $BACKUP_PARENT_DIR."
        return 1
    fi

    local total_versions=${#versions[@]}

    while true; do
        echo -e "\nAvailable versions:"
        local end_index=$total_versions
        if ! $show_full_list && [ $total_versions -gt $num_to_show ]; then
            end_index=$num_to_show
            echo "**Showing 5 most recent**:"
        fi

        for ((i=0; i<$end_index; i++)); do
            echo "$((i+1)). ${versions[$i]}"
        done

        local max_choice=$end_index
        if ! $show_full_list && [ $total_versions -gt $num_to_show ]; then
            echo "$((end_index+1)). [Show All $total_versions Versions]"
            max_choice=$((end_index+1))
        fi
        
        local cancel_choice=$((max_choice+1))
        echo "$cancel_choice. [Cancel Selection]"

        read -p "$prompt_message (1-$cancel_choice): " choice

        if [[ "$choice" == "$cancel_choice" ]]; then return 1; fi
        
        if [[ "$choice" == "$((end_index+1))" ]] && ! $show_full_list && [ $total_versions -gt $num_to_show ]; then
            show_full_list=true
            continue
        fi

        if [[ "$choice" =~ ^[0-9]+$ ]] && (( choice >= 1 && choice <= total_versions )); then
            SELECTED_VERSION_PATH="${BACKUP_PARENT_DIR}${versions[$((choice-1))]}"
            return 0
        fi
        echo "❌ Invalid choice."
    done
}

# --- Main Script ---
check_mounts

echo -e "\n\t✨ Deployment Script ✨"
echo "1. Backup current"
echo "2. Revert to older"
echo "3. Backup AND then Revert"
echo "4. Revert HTML Parent only"
echo "5. Abort"
read -p "Selection: " action_choice

case "$action_choice" in
    1)
        read -p "Version ID (e.g. v8.01): " version
        [[ -z "$version" ]] && exit 1
        DEST="${BACKUP_PARENT_DIR}MySportManager$version"
        perform_rsync "$SOURCE_DIR" "$DEST" "Backing up"
        ;;
    2|3)
        if [ "$action_choice" == "3" ]; then
            read -p "Backup Label: " version
            perform_rsync "$SOURCE_DIR" "${BACKUP_PARENT_DIR}MySportManager${version}_PRE" "Pre-revert backup"
        fi

        if select_version_dir "Choose version for $SOURCE_DIR"; then
            revert_path="$SELECTED_VERSION_PATH"
            read -p "Update $HTML_PARENT too? (y/n): " update_html
            if [[ ${update_html,,} == y* ]]; then
                perform_rsync "$revert_path" "$SOURCE_DIR" "Reverting" "revert"
                perform_rsync "$revert_path" "$HTML_PARENT" "Reverting HTML" "revert"
            else
                perform_rsync "$revert_path" "$SOURCE_DIR" "Reverting" "revert"
            fi
        fi
        ;;
    4)
        if select_version_dir "Choose version for $HTML_PARENT"; then
            perform_rsync "$SELECTED_VERSION_PATH" "$HTML_PARENT" "Reverting HTML" "revert"
        fi
        ;;
    5) exit 0 ;;
    *) echo "Invalid choice."; exit 1 ;;
esac