#!/bin/bash

BASE_URL="https://autoscript.interflazz.my.id/v2"
BRAND="INTERFLAZZ.MY.ID"
WHATSAPP="https://wa.me/6285956131443"
TELEGRAM="https://t.me/interflazz"

red="\e[91m"
green="\e[92m"
yellow="\e[93m"
blue="\e[94m"
purple="\e[95m"
cyan="\e[96m"
white="\e[97m"
orange="\e[38;5;130m"
bold_white="\e[1;37m"
reset="\e[0m"

DB_FILE="/etc/ssh/.ssh.db"

update_box_width() {
    local cols

    cols=$(tput cols 2>/dev/null || echo 80)

    if [ "$cols" -gt 72 ]; then
        BOX_WIDTH=72
    elif [ "$cols" -lt 30 ]; then
        BOX_WIDTH=30
    else
        BOX_WIDTH=$((cols - 2))
    fi

    BOX_INNER=$((BOX_WIDTH - 4))
}

repeat_char() {
    local count="$1"
    local char="$2"
    local line

    printf -v line '%*s' "$count" ""
    printf '%s' "${line// /$char}"
}

box_top() {
    update_box_width

    printf "%b┌" "$orange"
    repeat_char $((BOX_WIDTH - 2)) "─"
    printf "┐%b\n" "$reset"
}

box_middle() {
    update_box_width

    printf "%b├" "$orange"
    repeat_char $((BOX_WIDTH - 2)) "─"
    printf "┤%b\n" "$reset"
}

box_bottom() {
    update_box_width

    printf "%b└" "$orange"
    repeat_char $((BOX_WIDTH - 2)) "─"
    printf "┘%b\n" "$reset"
}

box_empty() {
    update_box_width

    printf "%b│%b" "$orange" "$reset"
    printf "%*s" $((BOX_WIDTH - 2)) ""
    printf "%b│%b\n" "$orange" "$reset"
}

box_center() {
    update_box_width

    local text="$1"
    local color="${2:-$white}"
    local length=${#text}
    local available="$BOX_INNER"

    if [ "$length" -gt "$available" ]; then
        box_left "$text" "$color"
        return
    fi

    local left=$(((available - length) / 2))
    local right=$((available - length - left))

    printf "%b│%b " "$orange" "$reset"
    printf "%*s" "$left" ""
    printf "%b%s%b" "$color" "$text" "$reset"
    printf "%*s" "$right" ""
    printf " %b│%b\n" "$orange" "$reset"
}

box_left() {
    update_box_width

    local text="$1"
    local color="${2:-$white}"
    local available="$BOX_INNER"
    local length=${#text}
    local offset=0
    local part
    local part_length
    local right

    if [ "$length" -eq 0 ]; then
        box_empty
        return
    fi

    while [ "$offset" -lt "$length" ]; do
        part="${text:$offset:$available}"
        part_length=${#part}
        right=$((available - part_length))

        printf "%b│%b " "$orange" "$reset"
        printf "%b%s%b" "$color" "$part" "$reset"
        printf "%*s" "$right" ""
        printf " %b│%b\n" "$orange" "$reset"

        offset=$((offset + available))
    done
}

show_access_denied() {
    local reason="$1"

    clear

    box_top
    box_center "$BRAND" "$green"
    box_center "AUTOSCRIPT PREMIUM" "$bold_white"
    box_middle
    box_center "AKSES DITOLAK!" "$red"
    box_middle
    box_left "IP VPS : $vps_ip" "$yellow"
    box_left "$reason" "$yellow"
    box_middle
    box_center "HUBUNGI ADMIN" "$bold_white"
    box_left "WhatsApp ~ $WHATSAPP" "$green"
    box_left "Telegram ~ $TELEGRAM" "$cyan"
    box_bottom

    exit 1
}

show_header() {
    clear

    box_top
    box_center "$BRAND" "$green"
    box_center "HAPUS AKUN SSH / OVPN" "$bold_white"
    box_bottom
}

get_days_left() {
    local exp="$1"
    local exp_timestamp
    local current_timestamp
    local days_left

    exp_timestamp=$(date -d "$exp" +%s 2>/dev/null)
    current_timestamp=$(date +%s)

    if [ -z "$exp_timestamp" ]; then
        echo "0"
        return
    fi

    days_left=$(((exp_timestamp - current_timestamp) / 86400))

    if [ "$days_left" -lt 0 ]; then
        days_left=0
    fi

    echo "$days_left"
}

cleanup_account_files() {
    local user="$1"

    rm -f \
        "/etc/ssh/${user}" \
        "/etc/xray/log-createssh-${user}.log" \
        "/var/www/html/ssh-${user}.txt"
}

restart_ssh() {
    if systemctl restart ssh >/dev/null 2>&1; then
        return 0
    fi

    if systemctl restart sshd >/dev/null 2>&1; then
        return 0
    fi

    return 1
}

vps_ip=$(wget -qO- ipv4.icanhazip.com)

if [ -z "$vps_ip" ]; then
    vps_ip=$(curl -4 -s ipv4.icanhazip.com)
fi

if [ -z "$vps_ip" ]; then
    vps_ip="Tidak diketahui"
fi

data_acc=$(
    curl -s "${BASE_URL}/access" |
        grep "### $vps_ip " |
        awk '{print $3}'
)

if [ -z "$data_acc" ]; then
    show_access_denied "VPS belum memiliki izin akses script."
fi

expiry_date=$(date -d "$data_acc" +%s 2>/dev/null)
current_date=$(date +%s)

if [ -z "$expiry_date" ]; then
    show_access_denied "Data masa aktif script tidak valid."
fi

if [ "$expiry_date" -le "$current_date" ]; then
    show_access_denied "Masa aktif akses script telah berakhir."
fi

remaining_days=$(((expiry_date - current_date) / 86400))

mkdir -p /etc/ssh

if [ ! -f "$DB_FILE" ]; then
    touch "$DB_FILE"
fi

show_header

account_count=$(grep -c '^### ' "$DB_FILE" 2>/dev/null)

if [ "$account_count" -eq 0 ]; then
    echo ""

    box_top
    box_center "TIDAK ADA AKUN" "$yellow"
    box_middle
    box_center "Belum ada akun SSH / OVPN yang tersedia." "$white"
    box_bottom

    exit 0
fi

echo ""

box_top
box_center "PILIH METODE" "$yellow"
box_middle
box_left "1. Pilih akun berdasarkan nomor" "$green"
box_left "2. Masukkan username secara manual" "$green"
box_bottom

echo ""

read -rp "Pilihan [1-2] : " delete_choice

case "$delete_choice" in
    1)
        show_header

        echo ""
        printf " ┌────┬────────────────────┬─────────────┐\n"
        printf " │ No │ Username           │ Sisa Aktif  │\n"
        printf " ├────┼────────────────────┼─────────────┤\n"

        index=1

        while read -r _ user exp; do
            [ -z "$user" ] && continue

            days_left=$(get_days_left "$exp")

            printf " │ %-2s │ %-18s │ %-9s   │\n" \
                "$index" \
                "$user" \
                "${days_left} hari"

            index=$((index + 1))
        done < <(grep '^### ' "$DB_FILE")

        printf " └────┴────────────────────┴─────────────┘\n"

        echo ""

        client_number=""

        while true; do
            read -rp "Pilih nomor akun [1-${account_count}] : " client_number

            if [[ "$client_number" =~ ^[0-9]+$ ]] &&
               [ "$client_number" -ge 1 ] &&
               [ "$client_number" -le "$account_count" ]; then
                break
            fi

            echo -e "${red}Nomor akun tidak valid.${reset}"
        done

        user=$(
            grep '^### ' "$DB_FILE" |
                awk '{print $2}' |
                sed -n "${client_number}p"
        )

        exp=$(
            grep '^### ' "$DB_FILE" |
                awk '{print $3}' |
                sed -n "${client_number}p"
        )
        ;;

    2)
        echo ""

        read -rp "Masukkan username : " user

        if [ -z "$user" ]; then
            echo -e "${red}Username tidak boleh kosong.${reset}"
            exit 1
        fi

        if ! [[ "$user" =~ ^[a-zA-Z0-9_-]+$ ]]; then
            echo -e "${red}Format username tidak valid.${reset}"
            exit 1
        fi

        if ! grep -q "^### ${user} " "$DB_FILE"; then
            echo ""

            box_top
            box_center "AKUN TIDAK DITEMUKAN" "$red"
            box_middle
            box_left "Username : $user" "$yellow"
            box_bottom

            exit 1
        fi

        exp=$(
            grep "^### ${user} " "$DB_FILE" |
                head -1 |
                awk '{print $3}'
        )
        ;;

    *)
        echo ""

        box_top
        box_center "PILIHAN TIDAK VALID" "$red"
        box_middle
        box_center "Silakan pilih nomor 1 atau 2." "$yellow"
        box_bottom

        exit 1
        ;;
esac

if [ -z "$user" ] || [ -z "$exp" ]; then
    echo ""

    box_top
    box_center "DATA AKUN TIDAK VALID" "$red"
    box_middle
    box_center "Gagal membaca informasi akun SSH." "$yellow"
    box_bottom

    exit 1
fi

show_header

echo ""

box_top
box_center "AKUN TERPILIH" "$yellow"
box_middle
box_left "Username       : $user" "$white"
box_left "Kadaluarsa     : $exp" "$white"
box_left "Sisa Aktif     : $(get_days_left "$exp") Hari" "$white"
box_bottom

echo ""

read -rp "Yakin ingin menghapus akun ini? [y/N] : " confirm

case "$confirm" in
    y|Y|yes|YES|ya|YA|Ya)
        ;;
    *)
        echo ""

        box_top
        box_center "PENGHAPUSAN DIBATALKAN" "$yellow"
        box_middle
        box_left "Akun $user tidak dihapus." "$white"
        box_bottom

        exit 0
        ;;
esac

if id "$user" >/dev/null 2>&1; then
    pkill -u "$user" >/dev/null 2>&1 || true

    if ! userdel -f "$user" >/dev/null 2>&1; then
        echo ""

        box_top
        box_center "GAGAL MENGHAPUS AKUN" "$red"
        box_middle
        box_left "User Linux $user gagal dihapus." "$yellow"
        box_left "Periksa akun menggunakan: id $user" "$white"
        box_bottom

        exit 1
    fi
fi

sed -i "/^### ${user} /d" "$DB_FILE"

cleanup_account_files "$user"

restart_status="berhasil"

if ! restart_ssh; then
    restart_status="gagal"
fi

clear

box_top
box_center "$BRAND" "$green"
box_center "HAPUS AKUN SSH / OVPN" "$bold_white"
box_middle
box_center "AKUN BERHASIL DIHAPUS" "$green"
box_middle
box_left "Username       : $user" "$white"
box_left "Kadaluarsa     : $exp" "$white"

if [ "$restart_status" = "berhasil" ]; then
    box_left "Layanan SSH    : Berhasil dimulai ulang" "$green"
else
    box_left "Layanan SSH    : Gagal dimulai ulang" "$red"
fi

box_middle

if [ "$restart_status" = "gagal" ]; then
    box_left "Akun tetap sudah dihapus dari database." "$yellow"
    box_left "Periksa: systemctl status ssh" "$yellow"
else
    box_center "Akun telah dihapus secara permanen." "$white"
fi

box_middle
box_left "WhatsApp ~ $WHATSAPP" "$green"
box_left "Telegram ~ $TELEGRAM" "$cyan"
box_bottom

exit 0