#!/usr/bin/env bash

set -euo pipefail

DB_HOST="${DB_HOST:-localhost}"
SSH_TARGET_USER="${SSH_TARGET_USER:-${USER:-}}"
LOCAL_LOG_DIR="${LOCAL_LOG_DIR:-${HOME}/tower-logs}"

if [[ -t 1 && "${TERM:-}" != "dumb" ]]; then
    COLOR_RESET=$'\033[0m'
    COLOR_BORDER=$'\033[1;34m'
    COLOR_HEADER=$'\033[1;36m'
    COLOR_OPTION=$'\033[1;33m'
    COLOR_PROMPT=$'\033[1;32m'
    COLOR_INFO=$'\033[0;37m'
    COLOR_ERROR=$'\033[1;31m'
else
    COLOR_RESET=""
    COLOR_BORDER=""
    COLOR_HEADER=""
    COLOR_OPTION=""
    COLOR_PROMPT=""
    COLOR_INFO=""
    COLOR_ERROR=""
fi

usage() {
    cat <<'EOF'
Usage:
  ./tower-connect

Environment:
  DB_HOST           PostgreSQL host used by the tower query
  SSH_TARGET_USER   SSH user to use when connecting to the selected tower
  LOCAL_LOG_DIR     Base directory for copied tower logs on the local server
EOF
}

for cmd in psql ssh scp; do
    command -v "$cmd" >/dev/null 2>&1 || {
        echo "ERROR: Required command '$cmd' is not installed or not in PATH."
        exit 1
    }
done

clear_screen() {
    if command -v clear >/dev/null 2>&1; then
        clear
    else
        printf '\033[2J\033[H'
    fi
}

print_divider() {
    printf '%s%s%s\n' "$COLOR_BORDER" "============================================================" "$COLOR_RESET"
}

print_panel_title() {
    local title="$1"
    echo
    print_divider
    printf '%s%s%s\n' "$COLOR_HEADER" "$title" "$COLOR_RESET"
    print_divider
    echo
}

print_option() {
    local key="$1"
    local label="$2"
    printf '  %s%s%s %s\n' "$COLOR_OPTION" "$key" "$COLOR_RESET" "$label"
}

print_prompt() {
    local prompt="$1"
    printf '%s%s%s' "$COLOR_PROMPT" "$prompt" "$COLOR_RESET"
}

read -r -d '' TOWER_QUERY <<'SQL' || true
SELECT
    dafe.tag AS instance_name,
    dafe.site_ip AS ssh_host
FROM equipment.dafe dafe
WHERE dafe.active = TRUE AND dafe.id > 1
ORDER BY dafe.id;
SQL

mapfile -t tower_rows < <(
    PGPASSWORD="${PGPASSWORD:-}" \
    psql \
        --host="$DB_HOST" \
        --port="5432" \
        --username="dsuper" \
        --dbname="dosis2" \
        --no-align \
        --tuples-only \
        --field-separator=$'\t' \
        --set=ON_ERROR_STOP=1 \
        -c "$TOWER_QUERY"
)

if [[ "${#tower_rows[@]}" -eq 0 ]]; then
    echo "No active towers were returned by the Tower query."
    exit 1
fi

clear_screen
print_panel_title "Available Towers"
for idx in "${!tower_rows[@]}"; do
    IFS=$'\t' read -r instance_name ssh_host <<<"${tower_rows[$idx]}"

    if [[ -z "${instance_name:-}" || -z "${ssh_host:-}" ]]; then
        echo "ERROR: Tower query returned an incomplete row: ${tower_rows[$idx]}"
        exit 1
    fi

    printf '  %s%2d)%s %s %s(%s)%s\n' \
        "$COLOR_OPTION" \
        "$((idx + 1))" \
        "$COLOR_RESET" \
        "$instance_name" \
        "$COLOR_INFO" \
        "$ssh_host" \
        "$COLOR_RESET"
done

echo
echo

remote_target_for() {
    local ssh_host="$1"

    if [[ -n "${SSH_TARGET_USER}" ]]; then
        printf '%s@%s' "$SSH_TARGET_USER" "$ssh_host"
    else
        printf '%s' "$ssh_host"
    fi
}

tower_menu() {
    local instance_name="$1"
    local ssh_host="$2"
    local remote_target
    remote_target="$(remote_target_for "$ssh_host")"

    while true; do
        print_panel_title "Selected Tower"
        printf '%s%s%s %s(%s)%s\n' \
            "$COLOR_HEADER" \
            "$instance_name" \
            "$COLOR_RESET" \
            "$COLOR_INFO" \
            "$ssh_host" \
            "$COLOR_RESET"
        echo
        print_option "1)" "SSH to tower"
        print_option "2)" "Copy /var/log/syslog to ${LOCAL_LOG_DIR}/${instance_name}/syslog"
        print_option "b)" "Back to tower list"
        print_option "q)" "Quit"
        echo
        print_prompt "Choose an option: "
        read -r action

        case "$action" in
            1)
                echo
                printf '%sConnecting to %s at %s...%s\n' "$COLOR_INFO" "$instance_name" "$ssh_host" "$COLOR_RESET"
                ssh "$remote_target"
                ;;
            2)
                dest_dir="${LOCAL_LOG_DIR}/${instance_name}"
                dest_file="${dest_dir}/syslog"
                mkdir -p "$dest_dir"
                echo
                printf '%sCopying /var/log/syslog from %s to %s...%s\n' "$COLOR_INFO" "$instance_name" "$dest_file" "$COLOR_RESET"
                scp "${remote_target}:/var/log/syslog" "$dest_file"
                ;;
            b|B|back)
                clear_screen
                print_panel_title "Available Towers"
                for idx in "${!tower_rows[@]}"; do
                    IFS=$'\t' read -r listed_instance_name listed_ssh_host <<<"${tower_rows[$idx]}"
                    printf '  %s%2d)%s %s %s(%s)%s\n' \
                        "$COLOR_OPTION" \
                        "$((idx + 1))" \
                        "$COLOR_RESET" \
                        "$listed_instance_name" \
                        "$COLOR_INFO" \
                        "$listed_ssh_host" \
                        "$COLOR_RESET"
                done
                echo
                echo
                return 0
                ;;
            q|Q|quit|exit)
                exit 0
                ;;
            *)
                printf '%sInvalid selection.%s\n' "$COLOR_ERROR" "$COLOR_RESET"
                ;;
        esac
    done
}

while true; do
    echo
    print_prompt "Select a tower [1-${#tower_rows[@]}, q to quit]: "
    read -r choice

    case "$choice" in
        q|Q|quit|exit)
            exit 0
            ;;
    esac

    if [[ "$choice" =~ ^[0-9]+$ ]] && (( choice >= 1 && choice <= ${#tower_rows[@]} )); then
        selected_row="${tower_rows[$((choice - 1))]}"
        IFS=$'\t' read -r instance_name ssh_host <<<"$selected_row"
        tower_menu "$instance_name" "$ssh_host"
        continue
    fi

    printf '%sInvalid selection.%s\n' "$COLOR_ERROR" "$COLOR_RESET"
done
