#!/usr/bin/env bash
# Interactive Debian-family post-install bootstrap.
set -Eeuo pipefail

SYNC_BASHRC_URL="${SYNC_BASHRC_URL:-https://gist.darto.id/dartokloning/82f93f1f0a294d55bd5f1a0abcb7f63f/download/HEAD/sync-bashrc-all.sh}"
SYNC_BASHRC_FILE="/usr/local/sbin/sync-bashrc-all.sh"
FAIL2BAN_JAIL="/etc/fail2ban/jail.d/sshd.local"
export DEBIAN_FRONTEND=noninteractive

log() { printf '\n== %s ==\n' "$*"; }
ok() { printf '  [OK] %s\n' "$*"; }
warn() { printf '  [!] %s\n' "$*" >&2; }
die() { printf 'ERROR: %s\n' "$*" >&2; exit 1; }
trap 'warn "Failed at line $LINENO (exit $?). Check the output above."' ERR

[[ $EUID -eq 0 ]] || die 'Run as root: use su - and then ./debian-post-install-v2.sh, or sudo ./debian-post-install-v2.sh'
[[ -t 0 ]] || die 'Interactive mode requires a terminal (stdin TTY).'
[[ -r /etc/os-release ]] || die '/etc/os-release was not found.'
. /etc/os-release
if [[ "${ID:-}" != debian && " ${ID_LIKE:-} " != *' debian '* ]]; then
    warn "Distribution ${PRETTY_NAME:-unknown} does not identify itself as Debian-based."
    command -v apt-get >/dev/null && command -v dpkg >/dev/null || die 'APT/dpkg is unavailable.'
    read -r -p 'Continue despite potential compatibility issues? [y/N] ' confirm
    [[ ${confirm,,} == y || ${confirm,,} == yes ]] || exit 0
fi
command -v apt-get >/dev/null && command -v dpkg >/dev/null || die 'APT/dpkg is required.'
command -v systemctl >/dev/null || die 'This script requires systemd.'

ask() {
    local reply
    while true; do
        read -r -p "$1 [Y/n] " reply || die 'Terminal input was closed.'
        case "${reply,,}" in
            ''|y|yes) return 0 ;;
            n|no) return 1 ;;
            *) warn 'Please answer y or n.' ;;
        esac
    done
}
ask_strict() {
    local reply
    while true; do
        read -r -p "$1 [y/N] " reply || die 'Terminal input was closed.'
        case "${reply,,}" in
            y|yes) return 0 ;;
            ''|n|no) return 1 ;;
            *) warn 'Please answer y or n.' ;;
        esac
    done
}

APT_UPDATED=0
install_packages() {
    if (( ! APT_UPDATED )); then
        apt-get update
        APT_UPDATED=1
    fi
    apt-get install -y "$@"
}

SSH_PORTS=()
detect_ssh_ports() {
    SSH_PORTS=()
    local sshd_bin='' p
    if [[ -x /usr/sbin/sshd ]]; then sshd_bin=/usr/sbin/sshd
    elif command -v sshd >/dev/null 2>&1; then sshd_bin=$(command -v sshd)
    fi
    if [[ -n $sshd_bin ]]; then
        while read -r p; do
            [[ $p =~ ^[0-9]+$ ]] && (( p >= 1 && p <= 65535 )) && SSH_PORTS+=("$p")
        done < <("$sshd_bin" -T 2>/dev/null | awk '$1=="port" {print $2}' | sort -un)
    fi
    # No silent port 22 fallback: user must verify when detection fails.
    if (( ${#SSH_PORTS[@]} == 0 )); then
        warn 'SSH ports could not be reliably detected.'
        read -r -p 'Enter the SSH TCP port in use (e.g., 22): ' p
        [[ $p =~ ^[0-9]+$ ]] && (( 10#$p >= 1 && 10#$p <= 65535 )) || die 'Invalid SSH port.'
        SSH_PORTS=("$((10#$p))")
    fi
    ok "Port SSH: ${SSH_PORTS[*]}"
}

status=()
record() { status+=("$1: $2"); }

log "Debian Post Install v2 — ${PRETTY_NAME:-unknown}"
printf 'You will be prompted before each task. Press Enter to select Yes.\n'

if ask '1. Install sudo and select users to grant sudo access?'; then
    install_packages sudo
    mapfile -t users < <(getent passwd | awk -F: '$3 >= 1000 && $3 < 65534 && $7 !~ /(nologin|false)$/ {print $1}' | sort -u)
    if (( ${#users[@]} == 0 )); then
        warn 'No regular login users found. Sudo was installed, but no users were added.'
        record sudo 'installed; no users selected'
    else
        printf 'Available local users:\n'
        for i in "${!users[@]}"; do printf '  %d) %s\n' "$((i+1))" "${users[i]}"; done
        read -r -p 'User numbers (separate with spaces or commas; blank to skip): ' selection
        selection=${selection//,/ }
        declare -A seen=()
        selected=()
        for number in $selection; do
            [[ $number =~ ^[0-9]+$ ]] || die "Selection is not a number: $number"
            (( number >= 1 && number <= ${#users[@]} )) || die "Selection is out of range: $number"
            user=${users[number-1]}
            [[ -v seen[$user] ]] && continue
            seen[$user]=1
            selected+=("$user")
        done
        if (( ${#selected[@]} )); then
            printf 'Accounts to add to the sudo group: %s\n' "${selected[*]}"
            if ask_strict 'Confirm granting administrative privileges?'; then
                for user in "${selected[@]}"; do
                    usermod -aG sudo "$user"
                    ok "$user added to the sudo group (effective at next login)."
                done
                record sudo "user: ${selected[*]}"
            else
                record sudo 'user additions canceled'
            fi
        else
            record sudo 'installed; user additions skipped'
        fi
    fi
else record sudo 'skipped'; fi

if ask '2. Install and enable vnStat?'; then
    install_packages vnstat
    systemctl enable --now vnstat
    record vnStat "$(systemctl is-active vnstat || true)"
else record vnStat 'skipped'; fi

if ask '3. Install Vim?'; then
    install_packages vim vim-common
    command -v vim >/dev/null || die 'Vim was not found.'
    record Vim 'installed'
else record Vim 'skipped'; fi

if ask '4. Download and run global Bash/Fastfetch synchronization?'; then
    warn 'This task runs an external script as root and may change system-wide settings.'
    if ask_strict 'Do you trust the source and want to execute it?'; then
        install_packages curl ca-certificates
        tmp_sync=$(mktemp)
        if curl -fsSL "$SYNC_BASHRC_URL" -o "$tmp_sync" && [[ -s $tmp_sync ]]; then
            bash -n "$tmp_sync" || die 'The synchronization script has invalid Bash syntax.'
            install -o root -g root -m 0755 "$tmp_sync" "$SYNC_BASHRC_FILE"
            rm -f "$tmp_sync"
            "$SYNC_BASHRC_FILE"
            record Bash/Fastfetch 'synchronization completed'
        else
            rm -f "$tmp_sync"
            die 'Failed to download the synchronization script.'
        fi
    else record Bash/Fastfetch 'canceled'; fi
else record Bash/Fastfetch 'skipped'; fi

if ask '5. Install and configure UFW?'; then
    install_packages ufw
    detect_ssh_ports
    for port in "${SSH_PORTS[@]}"; do ufw allow "${port}/tcp" comment 'SSH'; done
    warn 'Review SSH ports and application rules (HAProxy, HTTP/HTTPS, etc.) before enabling UFW.'
    ufw status verbose || true
    if ask_strict 'Enable UFW now? Make sure your remote connection will remain accessible.'; then
        ufw --force enable
        systemctl enable --now ufw
        ufw status verbose
        record UFW 'enabled'
    else record UFW 'installed; not enabled by this script'; fi
else record UFW 'skipped'; fi

if ask '6. Install and configure Fail2ban for SSH?'; then
    install_packages fail2ban python3-systemd
    detect_ssh_ports
    if [[ -e $FAIL2BAN_JAIL ]]; then
        backup="${FAIL2BAN_JAIL}.bak.$(date +%Y%m%d-%H%M%S)"
        cp -a "$FAIL2BAN_JAIL" "$backup"
        ok "Configuration backup: $backup"
    fi
    if command -v ufw >/dev/null && ufw status 2>/dev/null | grep -q '^Status: active'; then
        ban_action=ufw
    else
        ban_action=iptables-multiport
        install_packages iptables
        warn 'UFW is inactive; using the iptables-multiport ban action.'
    fi
    mkdir -p /etc/fail2ban/jail.d
    ports_csv=$(IFS=,; echo "${SSH_PORTS[*]}")
    cat > "$FAIL2BAN_JAIL" <<JAIL
[sshd]
enabled = true
backend = systemd
port = ${ports_csv}
bantime = 4w
maxretry = 2
banaction = ${ban_action}
JAIL
    chmod 0644 "$FAIL2BAN_JAIL"
    fail2ban-client -t || die 'Fail2ban validation failed; inspect the jail file and backup.'
    systemctl enable --now fail2ban
    systemctl restart fail2ban
    systemctl is-active --quiet fail2ban || die 'Fail2ban failed to start.'
    record Fail2ban "active; ports ${ports_csv}; action ${ban_action}"
else record Fail2ban 'skipped'; fi

log 'Summary'
for line in "${status[@]}"; do printf '  - %s\n' "$line"; done
ok 'Completed. Sudo group membership changes take effect after users log in again.'
