#!/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"

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_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
        printf "%b│%b" "$orange" "$reset"
        printf "%*s" $((BOX_WIDTH - 2)) ""
        printf "%b│%b\n" "$orange" "$reset"
        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 service="$1"

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

    return 1
}

auto_remove() {
    local service="$1"
    local db_path="$2"
    local config_path="$3"
    local base_path="$4"
    local web_prefix="$5"
    local user
    local exp
    local exp_timestamp
    local current_timestamp
    local restart_needed=0

    if [ ! -f "$db_path" ]; then
        return
    fi

    mapfile -t data < <(
        grep '^### ' "$db_path" 2>/dev/null |
            awk '{print $2}' |
            sort -u
    )

    current_timestamp=$(date -d "$(date +%Y-%m-%d)" +%s)

    for user in "${data[@]}"; do
        [ -z "$user" ] && continue

        exp=$(
            grep "^### ${user} " "$db_path" 2>/dev/null |
                head -1 |
                awk '{print $3}'
        )

        [ -z "$exp" ] && continue

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

        [ -z "$exp_timestamp" ] && continue

        if [ "$exp_timestamp" -le "$current_timestamp" ]; then
            if [ -f "$config_path" ]; then
                sed -i "/^### ${user} ${exp}$/,+1d" "$config_path"
            fi

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

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

            restart_needed=1
        fi
    done

    if [ "$restart_needed" -eq 1 ]; then
        if ! restart_service "$service"; then
            echo -e "${yellow}Peringatan: gagal memulai ulang layanan ${service}@config.${reset}"
        fi
    fi
}

auto_remove_ssh() {
    local db_path="/etc/ssh/.ssh.db"
    local user
    local exp
    local exp_timestamp
    local current_timestamp
    local restart_needed=0

    if [ ! -f "$db_path" ]; then
        return
    fi

    mapfile -t data < <(
        grep '^### ' "$db_path" 2>/dev/null |
            awk '{print $2}' |
            sort -u
    )

    current_timestamp=$(date -d "$(date +%Y-%m-%d)" +%s)

    for user in "${data[@]}"; do
        [ -z "$user" ] && continue

        exp=$(
            grep "^### ${user} " "$db_path" 2>/dev/null |
                head -1 |
                awk '{print $3}'
        )

        [ -z "$exp" ] && continue

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

        [ -z "$exp_timestamp" ] && continue

        if [ "$exp_timestamp" -le "$current_timestamp" ]; then
            if id "$user" >/dev/null 2>&1; then
                pkill -u "$user" >/dev/null 2>&1 || true
                userdel -f "$user" >/dev/null 2>&1 || true
            fi

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

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

            restart_needed=1
        fi
    done

    if [ "$restart_needed" -eq 1 ]; then
        if systemctl restart ssh >/dev/null 2>&1; then
            return
        fi

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

        echo -e "${yellow}Peringatan: gagal memulai ulang layanan SSH.${reset}"
    fi
}

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

auto_remove \
    "vmess" \
    "/etc/xray/vmess/.vmess.db" \
    "/etc/xray/vmess/config.json" \
    "/etc/xray/vmess" \
    "vmess"

auto_remove \
    "vless" \
    "/etc/xray/vless/.vless.db" \
    "/etc/xray/vless/config.json" \
    "/etc/xray/vless" \
    "vless"

auto_remove \
    "trojan" \
    "/etc/xray/trojan/.trojan.db" \
    "/etc/xray/trojan/config.json" \
    "/etc/xray/trojan" \
    "trojan"

auto_remove \
    "shadowsocks" \
    "/etc/xray/shadowsocks/.shadowsocks.db" \
    "/etc/xray/shadowsocks/config.json" \
    "/etc/xray/shadowsocks" \
    "shadowsocks"

auto_remove_ssh

exit 0