#!/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"
yellow="\e[38;5;226m"
cyan="\e[38;5;51m"
white="\e[97m"
orange="\e[38;5;130m"
bold_white="\e[1;37m"
reset="\e[0m"

mode="${1:-}"
user="${2:-}"
timer="${3:-}"

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
}

restart_service() {
    local protocol="$1"

    if systemctl restart "${protocol}@config" >/dev/null 2>&1; then
        return 0
    fi

    return 1
}

cleanup_xray_account() {
    local protocol="$1"
    local config_file="/etc/xray/${protocol}/config.json"
    local db_file="/etc/xray/${protocol}/.${protocol}.db"
    local exp

    if [ -f "$config_file" ]; then
        exp=$(
            grep "^### ${user} " "$config_file" 2>/dev/null |
                head -1 |
                awk '{print $3}'
        )

        if [ -n "$exp" ]; then
            sed -i "/^### ${user} ${exp}$/,+1d" "$config_file"
        else
            sed -i "/^### ${user} /,+1d" "$config_file"
        fi
    fi

    if [ -f "$db_file" ]; then
        sed -i "/^### ${user} /d" "$db_file"
    fi

    rm -f \
        "/etc/xray/${protocol}/${user}" \
        "/etc/xray/${protocol}/${user}IP" \
        "/etc/xray/${protocol}/usage/${user}" \
        "/etc/xray/${protocol}/log-create-${user}.log" \
        "/etc/xray/${protocol}/${user}-non.json" \
        "/etc/xray/${protocol}/${user}-tls.json" \
        "/etc/xray/${protocol}/${user}-grpc.json" \
        "/var/www/html/${protocol}-${user}.txt"

    restart_service "$protocol"
}

trial_vmess() {
    sleep "${timer}m"
    cleanup_xray_account "vmess"
}

trial_vless() {
    sleep "${timer}m"
    cleanup_xray_account "vless"
}

trial_trojan() {
    sleep "${timer}m"
    cleanup_xray_account "trojan"
}

trial_shadowsocks() {
    sleep "${timer}m"
    cleanup_xray_account "shadowsocks"
}

trial_ssh() {
    sleep "${timer}m"

    if getent passwd "$user" >/dev/null 2>&1; then
        pkill -u "$user" >/dev/null 2>&1 || true
        userdel -f "$user" >/dev/null 2>&1
    fi

    if [ -f "/etc/ssh/.ssh.db" ]; then
        sed -i "/^### ${user} /d" /etc/ssh/.ssh.db
    fi

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

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

    systemctl restart sshd >/dev/null 2>&1 || true
}

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

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 ! [[ "$timer" =~ ^[1-9][0-9]*$ ]]; then
    echo -e "${red}Waktu trial harus berupa angka lebih dari 0 menit.${reset}"
    exit 1
fi

case "$mode" in
    trialws)
        trial_vmess
        ;;
    trialvl)
        trial_vless
        ;;
    trialtr)
        trial_trojan
        ;;
    trialss)
        trial_shadowsocks
        ;;
    trialssh)
        trial_ssh
        ;;
    *)
        echo -e "${red}Perintah tidak valid.${reset}"
        echo "Gunakan:"
        echo "trial trialws username menit"
        echo "trial trialvl username menit"
        echo "trial trialtr username menit"
        echo "trial trialss username menit"
        echo "trial trialssh username menit"
        exit 1
        ;;
esac

exit 0