#!/bin/bash
#
# debian-post-install.sh
#
# Bootstrap Debian fresh install:
#   - sudo + add user to sudo group
#   - vnStat
#   - Vim
#   - sync global .bashrc / shell prompt / Fastfetch config
#   - UFW firewall
#   - Fail2ban for SSH
#
# Jalankan sebagai root setelah:
#   su -
#
# Contoh:
#   chmod +x bootstrap-debian.sh
#   ./debian-post-install.sh
#
# Aman dijalankan ulang (idempotent).

set -Eeuo pipefail

# ---------------------------------------------------------------------------
# Configuration
# ---------------------------------------------------------------------------

ADMIN_USER="${ADMIN_USER:-darto}"

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"

# Port web yang biasa dibuka.
ALLOW_HTTP="${ALLOW_HTTP:-yes}"
ALLOW_HTTPS="${ALLOW_HTTPS:-yes}"

# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------

log() {
    printf '\n== %s ==\n' "$*"
}

ok() {
    printf '  -> %s\n' "$*"
}

die() {
    printf 'ERROR: %s\n' "$*" >&2
    exit 1
}

if [[ "$(id -u)" -ne 0 ]]; then
    die "Jalankan script ini sebagai root. Gunakan: su -"
fi

if [[ ! -r /etc/os-release ]]; then
    die "/etc/os-release tidak ditemukan."
fi

# Detect Debian and Debian-based distributions
if [[ ! -r /etc/os-release ]]; then
    die "/etc/os-release tidak ditemukan."
fi

. /etc/os-release

DISTRO_ID="${ID:-unknown}"
DISTRO_LIKE=" ${ID_LIKE:-} "

if [[ "$DISTRO_ID" == "debian" ]] ||
   [[ "$DISTRO_LIKE" == *" debian "* ]]; then
    ok "Distribusi kompatibel: ${PRETTY_NAME:-unknown}"
else
    die "Distribusi tidak didukung: ${PRETTY_NAME:-unknown}"
fi

if ! id "$ADMIN_USER" >/dev/null 2>&1; then
    die "User '$ADMIN_USER' tidak ditemukan."
fi

export DEBIAN_FRONTEND=noninteractive

# ---------------------------------------------------------------------------
# 1. Update + packages
# ---------------------------------------------------------------------------

log "1. Update repository dan install paket dasar"

apt-get update

apt-get install -y \
    sudo \
    curl \
    ca-certificates \
    inxi \
    vnstat \
    vim \
    vim-common \
    ufw \
    fail2ban

ok "Paket dasar sudah terinstall."

# ---------------------------------------------------------------------------
# 2. Sudo access
# ---------------------------------------------------------------------------

log "2. Pastikan $ADMIN_USER masuk group sudo"

if id -nG "$ADMIN_USER" | tr ' ' '\n' | grep -qx sudo; then
    ok "$ADMIN_USER sudah menjadi anggota group sudo."
else
    usermod -aG sudo "$ADMIN_USER"
    ok "$ADMIN_USER ditambahkan ke group sudo."
fi

printf '  -> Group %s: %s\n' "$ADMIN_USER" "$(id -nG "$ADMIN_USER")"

# ---------------------------------------------------------------------------
# 3. vnStat
# ---------------------------------------------------------------------------

log "3. Aktifkan vnStat"

systemctl enable --now vnstat
systemctl is-active --quiet vnstat \
    && ok "vnstat aktif." \
    || die "vnstat gagal aktif."

# ---------------------------------------------------------------------------
# 4. Vim
# ---------------------------------------------------------------------------

log "4. Verifikasi Vim"

if command -v vim >/dev/null 2>&1; then
    ok "Vim tersedia: $(vim --version | head -n1)"
else
    die "Vim tidak ditemukan setelah instalasi."
fi

# ---------------------------------------------------------------------------
# 5. Sync .bashrc / prompt / Fastfetch
# ---------------------------------------------------------------------------

log "5. Download dan jalankan sync-bashrc-all.sh"

tmp_sync="$(mktemp)"
trap 'rm -f "$tmp_sync"' EXIT

curl -fL --silent --show-error "$SYNC_BASHRC_URL" -o "$tmp_sync"

if [[ ! -s "$tmp_sync" ]]; then
    die "sync-bashrc-all.sh hasil download kosong."
fi

install -o root -g root -m 0755 "$tmp_sync" "$SYNC_BASHRC_FILE"

ok "sync-bashrc-all.sh disimpan di $SYNC_BASHRC_FILE"

"$SYNC_BASHRC_FILE"

ok "Konfigurasi Bash/Fastfetch selesai disinkronkan."

# ---------------------------------------------------------------------------
# 6. Detect SSH port
# ---------------------------------------------------------------------------

log "6. Deteksi port SSH"

SSH_PORT="22"

if command -v sshd >/dev/null 2>&1; then
    detected_port="$(sshd -T 2>/dev/null | awk '$1=="port" {print $2; exit}' || true)"
    if [[ "$detected_port" =~ ^[0-9]+$ ]]; then
        SSH_PORT="$detected_port"
    fi
fi

ok "Port SSH terdeteksi: $SSH_PORT/tcp"

# ---------------------------------------------------------------------------
# 7. UFW
# ---------------------------------------------------------------------------

log "7. Konfigurasi UFW"

# Jangan reset UFW agar rule custom yang mungkin sudah ada tidak hilang.
ufw allow "${SSH_PORT}/tcp" comment 'SSH'

#if [[ "$ALLOW_HTTP" == "yes" ]]; then
#    ufw allow 80/tcp comment 'HTTP'
#fi

#if [[ "$ALLOW_HTTPS" == "yes" ]]; then
#    ufw allow 443/tcp comment 'HTTPS'
#fi

# ufw --force enable aman untuk noninteractive.
ufw --force enable
systemctl enable --now ufw

ok "UFW aktif."

ufw status verbose

# ---------------------------------------------------------------------------
# 8. Fail2ban
# ---------------------------------------------------------------------------

log "8. Konfigurasi Fail2ban"

mkdir -p /etc/fail2ban/jail.d

cat > "$FAIL2BAN_JAIL" <<EOF
[sshd]
enabled = true
backend = systemd
port = ${SSH_PORT}
bantime = 4w
maxretry = 2
banaction = ufw
EOF

chmod 0644 "$FAIL2BAN_JAIL"

ok "Konfigurasi dibuat: $FAIL2BAN_JAIL"

# Validasi konfigurasi sebelum restart.
if ! fail2ban-client -t; then
    die "Validasi konfigurasi Fail2ban gagal."
fi

systemctl enable --now fail2ban
systemctl restart fail2ban

sleep 1

systemctl is-active --quiet fail2ban \
    && ok "Fail2ban aktif." \
    || die "Fail2ban gagal aktif."

# ---------------------------------------------------------------------------
# 9. Summary
# ---------------------------------------------------------------------------

log "9. Ringkasan"

printf 'User admin     : %s\n' "$ADMIN_USER"
printf 'Group          : %s\n' "$(id -nG "$ADMIN_USER")"
printf 'SSH port       : %s/tcp\n' "$SSH_PORT"
printf 'vnStat         : %s\n' "$(systemctl is-active vnstat || true)"
printf 'UFW            : %s\n' "$(systemctl is-active ufw || true)"
printf 'Fail2ban       : %s\n' "$(systemctl is-active fail2ban || true)"
printf 'Fail2ban jail  : %s\n' "$FAIL2BAN_JAIL"
printf 'Bash sync      : %s\n' "$SYNC_BASHRC_FILE"

echo
echo "Fail2ban SSH jail:"
fail2ban-client status sshd 2>/dev/null || true

echo
echo "============================================================"
echo "BOOTSTRAP DEBIAN SELESAI"
echo "============================================================"
echo
echo "PENTING:"
echo "User '$ADMIN_USER' baru memperoleh group sudo pada login session berikutnya."
echo "Disconnect SSH lalu login kembali sebagai '$ADMIN_USER'."
echo
echo "Setelah login ulang, cek:"
echo "  sudo -v"
echo "  groups"
echo "  fastfetch --config /etc/fastfetch/config.jsonc"
echo "  sudo ufw status verbose"
echo "  sudo fail2ban-client status sshd"
echo
