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

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
}

cek_status() {
    local service="$1"

    if systemctl is-active --quiet "$service"; then
        printf "%bAKTIF%b" "$green" "$reset"
    else
        printf "%bNONAKTIF%b" "$red" "$reset"
    fi
}

install_node_dependencies() {
    if ! command -v node >/dev/null 2>&1; then
        box_top
        box_center "$BRAND" "$green"
        box_middle
        box_center "NODE.JS TIDAK DITEMUKAN" "$red"
        box_middle
        box_left "Silakan install Node.js terlebih dahulu." "$yellow"
        box_bottom
        exit 1
    fi

    if ! command -v npm >/dev/null 2>&1; then
        box_top
        box_center "$BRAND" "$green"
        box_middle
        box_center "NPM TIDAK DITEMUKAN" "$red"
        box_middle
        box_left "Silakan install NPM terlebih dahulu." "$yellow"
        box_bottom
        exit 1
    fi

    echo -e "${yellow}[ • ] ${white}Memeriksa dependensi Bot Telegram...${reset}"

    if ! npm list \
        --prefix /root/.bot \
        express \
        telegraf \
        axios \
        moment \
        sqlite3 \
        >/dev/null 2>&1; then

        echo -e "${yellow}[ • ] ${white}Memasang dependensi Bot Telegram...${reset}"

        if ! npm install \
            --prefix /root/.bot \
            express \
            telegraf \
            axios \
            moment \
            sqlite3; then

            echo -e "${red}[ GAGAL ] Gagal memasang dependensi Node.js.${reset}"
            exit 1
        fi
    fi

    echo -e "${green}[ OK ] ${white}Dependensi Bot Telegram siap digunakan.${reset}"
}

setup_bot() {
    mkdir -p /root/.bot

    install_node_dependencies

    if [ ! -f "/root/.bot/app.js" ] || [ ! -f "/root/.bot/api.js" ]; then
        echo -e "${yellow}[ • ] ${white}Mengunduh file Bot Telegram...${reset}"

        rm -f /root/.bot/bot.zip

        if ! wget -q \
            -O /root/.bot/bot.zip \
            "${BASE_URL}/Files/bot.zip"; then

            echo -e "${red}[ GAGAL ] Gagal mengunduh bot.zip.${reset}"
            exit 1
        fi

        if [ ! -s "/root/.bot/bot.zip" ]; then
            echo -e "${red}[ GAGAL ] File bot.zip kosong.${reset}"
            rm -f /root/.bot/bot.zip
            exit 1
        fi

        echo -e "${yellow}[ • ] ${white}Mengekstrak file Bot Telegram...${reset}"

        if ! unzip -o \
            /root/.bot/bot.zip \
            -d /root/.bot \
            >/dev/null 2>&1; then

            echo -e "${red}[ GAGAL ] Gagal mengekstrak bot.zip.${reset}"
            rm -f /root/.bot/bot.zip
            exit 1
        fi

        rm -f /root/.bot/bot.zip
    fi

    if [ ! -f "/root/.bot/app.js" ]; then
        echo -e "${red}[ GAGAL ] File /root/.bot/app.js tidak ditemukan.${reset}"
        exit 1
    fi

    if [ ! -f "/root/.bot/api.js" ]; then
        echo -e "${red}[ GAGAL ] File /root/.bot/api.js tidak ditemukan.${reset}"
        exit 1
    fi

    find /root/.bot -type f -exec chmod +x {} \; >/dev/null 2>&1
}

client_api() {
    cat >/usr/bin/api <<EOF
#!/bin/bash
exec /usr/bin/node /root/.bot/api.js
EOF

    chmod +x /usr/bin/api

    cat >/etc/systemd/system/api.service <<EOF
[Unit]
Description=INTERFLAZZ.MY.ID API Service
After=network-online.target
Wants=network-online.target

[Service]
Type=simple
User=root
WorkingDirectory=/root/.bot
ExecStart=/usr/bin/api
Restart=always
RestartSec=3
Environment=NODE_ENV=production
Environment=PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin

[Install]
WantedBy=multi-user.target
EOF

    systemctl daemon-reload >/dev/null 2>&1
    systemctl enable api.service >/dev/null 2>&1

    if ! systemctl restart api.service >/dev/null 2>&1; then
        clear

        box_top
        box_center "$BRAND" "$green"
        box_center "API BOT TELEGRAM" "$bold_white"
        box_middle
        box_center "GAGAL MENJALANKAN API" "$red"
        box_middle
        box_left "Periksa status dengan:" "$yellow"
        box_left "systemctl status api.service" "$white"
        box_bottom

        exit 1
    fi

    sleep 1

    clear

    box_top
    box_center "$BRAND" "$green"
    box_center "API BOT TELEGRAM" "$bold_white"
    box_middle
    box_left "API Buat Akun" "$green"
    box_left "API Hapus Akun" "$green"
    box_left "API Renew Akun" "$green"
    box_left "API Cek Akun" "$green"
    box_middle

    if systemctl is-active --quiet api.service; then
        box_left "Status API : AKTIF" "$green"
    else
        box_left "Status API : NONAKTIF" "$red"
    fi

    box_middle
    box_left "WhatsApp ~ $WHATSAPP" "$green"
    box_left "Telegram ~ $TELEGRAM" "$blue"
    box_bottom
}

server_app() {
    clear

    box_top
    box_center "$BRAND" "$green"
    box_center "BOT TELEGRAM PREMIUM" "$bold_white"
    box_middle
    box_left "Buat akun VPN melalui Telegram" "$green"
    box_left "Hapus akun VPN melalui Telegram" "$green"
    box_left "Renew akun VPN melalui Telegram" "$green"
    box_left "Cek akun VPN melalui Telegram" "$green"
    box_middle
    box_center "KONFIGURASI BOT" "$yellow"
    box_bottom

    echo ""

    while true; do
        read -r -p "Masukkan Token Bot : " token

        if [ -z "$token" ]; then
            echo -e "${red}Token Bot tidak boleh kosong.${reset}"
            continue
        fi

        if ! [[ "$token" =~ ^[0-9]+:[A-Za-z0-9_-]+$ ]]; then
            echo -e "${red}Format Token Bot tidak valid.${reset}"
            continue
        fi

        break
    done

    while true; do
        read -r -p "Masukkan Admin ID : " adminid

        if [ -z "$adminid" ]; then
            echo -e "${red}Admin ID tidak boleh kosong.${reset}"
            continue
        fi

        if ! [[ "$adminid" =~ ^-?[0-9]+$ ]]; then
            echo -e "${red}Admin ID harus berupa angka.${reset}"
            continue
        fi

        break
    done

    rm -f /root/.bot/.vars.json

    cat >/root/.bot/.vars.json <<EOF
{
  "BOT_TOKEN": "$token",
  "ADMIN": [$adminid]
}
EOF

    chmod 600 /root/.bot/.vars.json

    cat >/etc/systemd/system/app.service <<EOF
[Unit]
Description=INTERFLAZZ.MY.ID Telegram Bot Service
After=network-online.target
Wants=network-online.target

[Service]
Type=simple
User=root
WorkingDirectory=/root/.bot
ExecStart=/usr/bin/node /root/.bot/app.js
Restart=always
RestartSec=3
Environment=PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
Environment=NODE_ENV=production

[Install]
WantedBy=multi-user.target
EOF

    systemctl daemon-reload >/dev/null 2>&1
    systemctl enable app.service >/dev/null 2>&1

    if ! systemctl restart app.service >/dev/null 2>&1; then
        clear

        box_top
        box_center "$BRAND" "$green"
        box_center "BOT TELEGRAM PREMIUM" "$bold_white"
        box_middle
        box_center "GAGAL MENJALANKAN BOT" "$red"
        box_middle
        box_left "Periksa status dengan:" "$yellow"
        box_left "systemctl status app.service" "$white"
        box_bottom

        exit 1
    fi

    sleep 1

    clear

    box_top
    box_center "$BRAND" "$green"
    box_center "BOT TELEGRAM PREMIUM" "$bold_white"
    box_middle

    if systemctl is-active --quiet app.service; then
        box_center "INSTALASI BOT BERHASIL" "$green"
        box_middle
        box_left "Status Bot : AKTIF" "$green"
    else
        box_center "BOT BELUM AKTIF" "$red"
        box_middle
        box_left "Status Bot : NONAKTIF" "$red"
    fi

    box_middle
    box_left "Bot Telegram siap digunakan." "$white"
    box_left "Ketik /start pada Bot Telegram." "$yellow"
    box_middle
    box_left "WhatsApp ~ $WHATSAPP" "$green"
    box_left "Telegram ~ $TELEGRAM" "$blue"
    box_bottom
}

show_usage() {
    clear

    box_top
    box_center "$BRAND" "$green"
    box_center "BOT TELEGRAM PREMIUM" "$bold_white"
    box_middle
    box_center "PERINTAH TIDAK VALID" "$red"
    box_middle
    box_left "Gunakan salah satu perintah berikut:" "$yellow"
    box_left "bot server" "$white"
    box_left "bot client" "$white"
    box_middle
    box_left "WhatsApp ~ $WHATSAPP" "$green"
    box_left "Telegram ~ $TELEGRAM" "$blue"
    box_bottom

    exit 1
}

case "${1:-}" in
    client)
        clear

        box_top
        box_center "$BRAND" "$green"
        box_center "INSTALASI API BOT" "$bold_white"
        box_middle
        box_center "Menyiapkan API Bot Telegram..." "$yellow"
        box_bottom

        echo ""

        setup_bot
        client_api
        ;;

    server)
        clear

        box_top
        box_center "$BRAND" "$green"
        box_center "INSTALASI BOT TELEGRAM" "$bold_white"
        box_middle
        box_center "Menyiapkan Bot Telegram..." "$yellow"
        box_bottom

        echo ""

        setup_bot
        server_app
        ;;

    *)
        show_usage
        ;;
esac