#!/bin/bash

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

green="\e[38;5;82m"
red="\e[38;5;196m"
neutral="\e[0m"
orange="\e[38;5;130m"
blue="\e[38;5;39m"
yellow="\e[38;5;226m"
purple="\e[38;5;141m"
bold_white="\e[1;37m"
reset="\e[0m"
pink="\e[38;5;205m"
white="\e[38;5;255m"
cyan="\e[38;5;51m"

DB_FILE="/etc/xray/shadowsocks/.shadowsocks.db"
CONFIG_FILE="/etc/xray/shadowsocks/config.json"

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 "SHADOWSOCKS MANAGER" "$bold_white"
    box_bottom
}

pause_menu() {
    echo ""
    read -n 1 -s -r -p "Tekan tombol apa saja untuk kembali..."
    echo ""
}

convert_size() {
    local bytes="${1:-0}"

    if ! [[ "$bytes" =~ ^[0-9]+$ ]]; then
        bytes=0
    fi

    if [ "$bytes" -lt 1024 ]; then
        echo "${bytes} B"
    elif [ "$bytes" -lt 1048576 ]; then
        echo "$(((bytes + 1023) / 1024)) KB"
    elif [ "$bytes" -lt 1073741824 ]; then
        echo "$(((bytes + 1048575) / 1048576)) MB"
    else
        echo "$(((bytes + 1073741823) / 1073741824)) GB"
    fi
}

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

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

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

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

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

    echo "$days_left"
}

ensure_database() {
    mkdir -p /etc/xray/shadowsocks/usage

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

get_account_count() {
    ensure_database
    grep -c '^### ' "$DB_FILE" 2>/dev/null || echo "0"
}

show_account_table() {
    local index=1
    local user
    local exp
    local credential
    local days_left

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

    while read -r marker user exp credential; do
        [ "$marker" != "###" ] && continue
        [ -z "$user" ] && continue

        days_left=$(get_days_left "$exp")

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

        index=$((index + 1))
    done <"$DB_FILE"

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

select_account() {
    local account_count
    local account_number

    account_count=$(get_account_count)

    if [ "$account_count" -eq 0 ]; then
        return 1
    fi

    echo ""
    show_account_table
    echo ""

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

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

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

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

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

    SELECTED_CREDENTIAL=$(
        grep '^### ' "$DB_FILE" |
            awk '{print $4}' |
            sed -n "${account_number}p"
    )

    [ -n "$SELECTED_USER" ]
}

shadowsocks_members() {
    local account_count
    local no=1
    local user
    local exp
    local credential
    local days_left
    local quota
    local ip_limit
    local usage
    local quota_text
    local usage_text

    clear

    box_top
    box_center "$BRAND" "$green"
    box_center "DAFTAR MEMBER SHADOWSOCKS" "$bold_white"
    box_bottom

    account_count=$(get_account_count)

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

        box_top
        box_center "TIDAK ADA AKUN" "$yellow"
        box_middle
        box_center "Belum ada akun Shadowsocks aktif." "$white"
        box_bottom

        pause_menu
        return
    fi

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

    while read -r marker user exp credential; do
        [ "$marker" != "###" ] && continue
        [ -z "$user" ] && continue

        days_left=$(get_days_left "$exp")

        quota=$(cat "/etc/xray/shadowsocks/${user}" 2>/dev/null)
        ip_limit=$(cat "/etc/xray/shadowsocks/${user}IP" 2>/dev/null)
        usage=$(cat "/etc/xray/shadowsocks/usage/${user}" 2>/dev/null)

        quota=${quota:-0}
        ip_limit=${ip_limit:-0}
        usage=${usage:-0}

        if [ "$quota" = "0" ]; then
            quota_text="Unlimited"
        else
            quota_text=$(convert_size "$quota")
        fi

        if [ "$ip_limit" = "0" ]; then
            ip_limit="∞"
        fi

        if [ "$usage" = "0" ]; then
            usage_text="0 B"
        else
            usage_text=$(convert_size "$usage")
        fi

        printf "│%-3s│%-14.14s│%-8.8s│%-10.10s│%-6.6s│%-10.10s│\n" \
            "$no" \
            "$user" \
            "${days_left} Hari" \
            "$quota_text" \
            "$ip_limit" \
            "$usage_text"

        no=$((no + 1))
    done <"$DB_FILE"

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

    pause_menu
}

change_shadowsocks_limit() {
    local account_count
    local username
    local new_quota
    local new_ip_limit
    local new_quota_bytes
    local quota_display
    local ip_display

    clear

    box_top
    box_center "$BRAND" "$green"
    box_center "UBAH LIMIT SHADOWSOCKS" "$bold_white"
    box_bottom

    account_count=$(get_account_count)

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

        box_top
        box_center "TIDAK ADA AKUN" "$yellow"
        box_middle
        box_center "Belum ada akun Shadowsocks aktif." "$white"
        box_bottom

        pause_menu
        return
    fi

    if ! select_account; then
        pause_menu
        return
    fi

    username="$SELECTED_USER"

    echo ""

    box_top
    box_center "AKUN TERPILIH" "$yellow"
    box_middle
    box_left "Username   : $username" "$white"
    box_left "Kadaluarsa : $SELECTED_EXP" "$white"
    box_bottom

    echo ""

    read -rp "Masukkan kuota baru GB [0 = Unlimited] : " new_quota
    read -rp "Masukkan batas IP baru [0 = Unlimited] : " new_ip_limit

    if ! [[ "$new_quota" =~ ^[0-9]+$ ]]; then
        echo -e "${red}Kuota harus berupa angka.${reset}"
        pause_menu
        return
    fi

    if ! [[ "$new_ip_limit" =~ ^[0-9]+$ ]]; then
        echo -e "${red}Batas IP harus berupa angka.${reset}"
        pause_menu
        return
    fi

    new_quota_bytes=$((new_quota * 1024 * 1024 * 1024))

    printf '%s\n' "$new_quota_bytes" \
        >"/etc/xray/shadowsocks/${username}"

    printf '%s\n' "$new_ip_limit" \
        >"/etc/xray/shadowsocks/${username}IP"

    if [ "$new_quota" -eq 0 ]; then
        quota_display="Unlimited"
    else
        quota_display="${new_quota} GB"
    fi

    if [ "$new_ip_limit" -eq 0 ]; then
        ip_display="Unlimited"
    else
        ip_display="$new_ip_limit"
    fi

    clear

    box_top
    box_center "$BRAND" "$green"
    box_center "LIMIT BERHASIL DIPERBARUI" "$bold_white"
    box_middle
    box_left "Username : $username" "$white"
    box_left "Kuota    : $quota_display" "$green"
    box_left "Batas IP : $ip_display" "$green"
    box_bottom

    pause_menu
}

shadowsocks_details() {
    local account_count
    local user
    local exp
    local password
    local quota
    local ip_limit
    local usage
    local quota_readable
    local usage_readable

    clear

    box_top
    box_center "$BRAND" "$green"
    box_center "DETAIL AKUN SHADOWSOCKS" "$bold_white"
    box_bottom

    account_count=$(get_account_count)

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

        box_top
        box_center "TIDAK ADA AKUN" "$yellow"
        box_middle
        box_center "Belum ada akun Shadowsocks terdaftar." "$white"
        box_bottom

        pause_menu
        return
    fi

    echo ""

    while read -r marker user exp password; do
        [ "$marker" != "###" ] && continue
        [ -z "$user" ] && continue

        quota=$(cat "/etc/xray/shadowsocks/${user}" 2>/dev/null)
        ip_limit=$(cat "/etc/xray/shadowsocks/${user}IP" 2>/dev/null)
        usage=$(cat "/etc/xray/shadowsocks/usage/${user}" 2>/dev/null)

        quota=${quota:-0}
        ip_limit=${ip_limit:-0}
        usage=${usage:-0}

        if [ "$quota" = "0" ]; then
            quota_readable="Unlimited"
        else
            quota_readable=$(convert_size "$quota")
        fi

        if [ "$ip_limit" = "0" ]; then
            ip_limit="Unlimited"
        fi

        if [ "$usage" = "0" ]; then
            usage_readable="0 B"
        else
            usage_readable=$(convert_size "$usage")
        fi

        box_top
        box_left "Username   : $user" "$white"
        box_left "Kadaluarsa : $exp" "$white"
        box_left "Password   : ${password:-Tidak tersedia}" "$white"
        box_left "Kuota      : $quota_readable" "$white"
        box_left "Batas IP   : $ip_limit" "$white"
        box_left "Pemakaian  : $usage_readable" "$white"
        box_bottom

        echo ""
    done <"$DB_FILE"

    pause_menu
}

custom_uuid_shadowsocks() {
    local account_count
    local user
    local exp
    local new_uuid
    local method="aes-256-gcm"

    clear

    box_top
    box_center "$BRAND" "$green"
    box_center "CUSTOM PASSWORD SHADOWSOCKS" "$bold_white"
    box_bottom

    account_count=$(get_account_count)

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

        box_top
        box_center "TIDAK ADA AKUN" "$yellow"
        box_middle
        box_center "Belum ada akun Shadowsocks aktif." "$white"
        box_bottom

        pause_menu
        return
    fi

    if ! select_account; then
        pause_menu
        return
    fi

    user="$SELECTED_USER"
    exp="$SELECTED_EXP"

    echo ""

    box_top
    box_center "AKUN TERPILIH" "$yellow"
    box_middle
    box_left "Username   : $user" "$white"
    box_left "Kadaluarsa : $exp" "$white"
    box_bottom

    echo ""

    while true; do
        read -rsp "Masukkan password baru minimal 6 karakter : " new_uuid
        echo ""

        if [ "${#new_uuid}" -ge 6 ] &&
           [[ "$new_uuid" =~ ^[a-zA-Z0-9_-]+$ ]]; then
            break
        fi

        echo -e "${red}Password minimal 6 karakter dan hanya boleh berisi huruf, angka, _ atau -.${reset}"
    done

    if [ ! -f "$CONFIG_FILE" ]; then
        echo -e "${red}File config Shadowsocks tidak ditemukan.${reset}"
        pause_menu
        return
    fi

    if ! grep -q '#ssws' "$CONFIG_FILE"; then
        echo -e "${red}Marker #ssws tidak ditemukan pada config.json.${reset}"
        pause_menu
        return
    fi

    if ! grep -q '#ssgrpc' "$CONFIG_FILE"; then
        echo -e "${red}Marker #ssgrpc tidak ditemukan pada config.json.${reset}"
        pause_menu
        return
    fi

    sed -i "/^### ${user} ${exp}$/,+1d" "$CONFIG_FILE"

    sed -i '/#ssws$/a\### '"$user $exp"'\
    },{"password": "'"$new_uuid"'","method": "'"$method"'","email": "'"$user"'"}' "$CONFIG_FILE"

    sed -i '/#ssgrpc$/a\### '"$user $exp"'\
    },{"password": "'"$new_uuid"'","method": "'"$method"'","email": "'"$user"'"}' "$CONFIG_FILE"

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

    printf '### %s %s %s\n' \
        "$user" \
        "$exp" \
        "$new_uuid" \
        >>"$DB_FILE"

    if systemctl restart shadowsocks@config >/dev/null 2>&1; then
        restart_status="Berhasil"
        restart_color="$green"
    else
        restart_status="Gagal"
        restart_color="$red"
    fi

    clear

    box_top
    box_center "$BRAND" "$green"
    box_center "PASSWORD BERHASIL DIPERBARUI" "$bold_white"
    box_middle
    box_left "Username : $user" "$white"
    box_left "Password : $new_uuid" "$green"
    box_left "Service  : $restart_status" "$restart_color"
    box_bottom

    pause_menu
}

run_command() {
    local command_name="$1"
    local label="$2"

    if command -v "$command_name" >/dev/null 2>&1; then
        "$command_name"
        return
    fi

    clear

    box_top
    box_center "$BRAND" "$green"
    box_center "$label" "$bold_white"
    box_middle
    box_center "PERINTAH TIDAK DITEMUKAN" "$red"
    box_middle
    box_left "Command : $command_name" "$yellow"
    box_bottom

    pause_menu
}

display_shadowsocks_menu() {
    local shadowsocks_choice

    while true; do
        clear

        box_top
        box_center "$BRAND" "$green"
        box_center "SHADOWSOCKS MANAGER" "$bold_white"
        box_middle
        box_left "1. Buat Akun Shadowsocks" "$green"
        box_left "2. Hapus Akun Shadowsocks" "$green"
        box_left "3. Renew Akun Shadowsocks" "$green"
        box_left "4. Cek Login Shadowsocks" "$green"
        box_left "5. Daftar Member Shadowsocks" "$green"
        box_left "6. Ubah Limit Akun Shadowsocks" "$green"
        box_left "7. Detail Akun Shadowsocks" "$green"
        box_left "8. Buat Akun Trial Shadowsocks" "$green"
        box_left "9. Custom Password Shadowsocks" "$green"
        box_left "X. Keluar" "$red"
        box_bottom

        echo ""

        read -rp "Pilih menu [1-9/X] : " shadowsocks_choice

        case "$shadowsocks_choice" in
            1)
                run_command "addshadowsocks" "BUAT AKUN SHADOWSOCKS"
                ;;
            2)
                run_command "dellshadowsocks" "HAPUS AKUN SHADOWSOCKS"
                ;;
            3)
                run_command "renewshadowsocks" "RENEW AKUN SHADOWSOCKS"
                ;;
            4)
                run_command "checkshadowsocks" "CEK LOGIN SHADOWSOCKS"
                ;;
            5)
                shadowsocks_members
                ;;
            6)
                change_shadowsocks_limit
                ;;
            7)
                shadowsocks_details
                ;;
            8)
                run_command "trialshadowsocks" "TRIAL SHADOWSOCKS"
                ;;
            9)
                custom_uuid_shadowsocks
                ;;
            x|X)
                clear

                box_top
                box_center "$BRAND" "$green"
                box_center "KELUAR DARI SHADOWSOCKS MANAGER" "$bold_white"
                box_middle
                box_center "Terima kasih telah menggunakan layanan kami." "$white"
                box_middle
                box_left "WhatsApp ~ $WHATSAPP" "$green"
                box_left "Telegram ~ $TELEGRAM" "$cyan"
                box_bottom

                exit 0
                ;;
            *)
                echo ""
                echo -e "${red}Pilihan tidak valid. Silakan coba kembali.${reset}"
                sleep 1
                ;;
        esac
    done
}

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))

ensure_database
display_shadowsocks_menu