#!/bin/bash
# cleanup-server - Dọn dẹp + nâng cấp server (Ubuntu/Arch), interactive, tuần tự.
# Cách dùng:
#   cleanup-server            # hiện menu chọn target (local hoặc server alias)
#   cleanup-server --run-steps   # (nội bộ) chạy thẳng 6 bước trên máy hiện tại

# -----------------------------
# Color helpers (tự tắt khi không phải TTY)
# -----------------------------
if [ -t 1 ]; then
    C_RESET=$'\033[0m'
    C_TITLE=$'\033[1;36m'   # tiêu đề
    C_OK=$'\033[1;32m'      # thành công
    C_DEL=$'\033[1;31m'     # sẽ xóa / lỗi
    C_WARN=$'\033[1;33m'    # cảnh báo
else
    C_RESET=""; C_TITLE=""; C_OK=""; C_DEL=""; C_WARN=""
fi

# -----------------------------
# Banner rainbow (giống style `cleanup`)
# -----------------------------
print_banner() {
    local use_color=0 reset="" i=0 line
    local -a lines=(
        '  ██████╗██╗   ██╗ ██████╗██╗  ██╗██╗   ██╗██████╗  ███████╗███╗   ██╗ ██████╗██╗  ██╗'
        ' ██╔════╝██║   ██║██╔════╝██║  ██║██║   ██║██╔══██╗ ██╔════╝████╗  ██║██╔═══██╗╚██╗██╔╝'
        ' ██║     ██║   ██║██║     ███████║██║   ██║██║  ██║ █████╗  ██╔██╗ ██║██║   ██║ ╚███╔╝ '
        ' ██║     ██║   ██║██║     ██╔══██║██║   ██║██║  ██║ ██╔══╝  ██║╚██╗██║██║   ██║ ██╔██╗ '
        ' ╚██████╗╚██████╔╝╚██████╗██║  ██║╚██████╔╝██████╔╝ ███████╗██║ ╚████║╚██████╔╝██╔╝ ██╗'
        '  ╚═════╝ ╚═════╝  ╚═════╝╚═╝  ╚═╝ ╚═════╝ ╚═════╝  ╚══════╝╚═╝  ╚═══╝ ╚═════╝ ╚═╝  ╚═╝'
    )
    local -a colors=()
    if [ -t 1 ]; then
        use_color=1
        reset=$'\033[0m'
        colors=(
            $'\033[1;38;5;51m' $'\033[1;38;5;87m' $'\033[1;38;5;123m'
            $'\033[1;38;5;159m' $'\033[1;38;5;220m' $'\033[1;38;5;214m'
        )
    fi
    echo ""
    for line in "${lines[@]}"; do
        if [ "$use_color" -eq 1 ]; then
            printf '%b%s%b\n' "${colors[$i]}" "$line" "$reset"
        else
            printf '%s\n' "$line"
        fi
        i=$((i + 1))
    done
    echo ""
}

# -----------------------------
# Danh sách target fix cứng (alias từ ~/.ssh/config)
# -----------------------------
TARGETS=("local" "ta" "toc" "oc" "cse" "vrc" "aws" "tk" "od")
TARGET_CURSOR=0
TARGET=""

# Vẽ menu single-select
draw_target_menu() {
    if [ "$1" = "redraw" ]; then
        printf '\033[%dA' "$(( ${#TARGETS[@]} + 2 ))"
    fi
    echo "  Chọn target (↑↓: di chuyển | Enter: chọn):"
    echo ""
    local i
    for ((i = 0; i < ${#TARGETS[@]}; i++)); do
        local prefix="  "
        if [ "$i" -eq "$TARGET_CURSOR" ]; then
            prefix="${C_TITLE}▸ ${C_RESET}"
        fi
        printf '\r\033[K%s%s\n' "$prefix" "${TARGETS[$i]}"
    done
}

# Chạy menu, đặt biến toàn cục TARGET
select_target() {
    draw_target_menu
    while true; do
        IFS= read -rsn1 key
        case "$key" in
            $'\x1b')
                read -rsn2 seq
                case "$seq" in
                    '[A') TARGET_CURSOR=$(( (TARGET_CURSOR - 1 + ${#TARGETS[@]}) % ${#TARGETS[@]} ));;
                    '[B') TARGET_CURSOR=$(( (TARGET_CURSOR + 1) % ${#TARGETS[@]} ));;
                esac
                ;;
            '')   # Enter
                echo ""
                TARGET="${TARGETS[$TARGET_CURSOR]}"
                return
                ;;
        esac
        draw_target_menu "redraw"
    done
}

# -----------------------------
# Main (phân nhánh theo argv)
# -----------------------------
main() {
    if [ "${1:-}" = "--run-steps" ]; then
        echo "${C_TITLE}===== 🧹 Cleanup-server (--run-steps) =====${C_RESET}"
        echo "    (chưa có bước nào — sẽ thêm ở task sau)"
        return
    fi
    print_banner
    echo "${C_TITLE}===== 🧹 Cleanup-server =====${C_RESET}"
    echo ""
    select_target
    echo "    Đã chọn target: ${C_TITLE}${TARGET}${C_RESET}  (chạy sẽ thêm ở Task 3)"
}

main "$@"
