#!/bin/bash

BASE_URL="https://autoscript.interflazz.my.id/v2"

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"

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 "INTERFLAZZ.MY.ID" "$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 ~ https://wa.me/6285956131443" "$green"
    box_left "Telegram ~ https://t.me/interflazz" "$cyan"
    box_bottom
}

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

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."
    exit 1
fi

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

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

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

ip=$(wget -qO- ipv4.icanhazip.com)
srv_date=$(curl -v --insecure --silent https://google.com/ 2>&1 | grep Date | sed -e 's/< Date: //')
date=$(date +"%Y-%m-%d" -d "$srv_date" 2>/dev/null)

city=$(cat /etc/xray/city 2>/dev/null || echo "Tidak diketahui")
pubkey=$(cat /etc/slowdns/server.pub 2>/dev/null || echo "Public key tidak tersedia")
ns_domain=$(cat /etc/xray/dns 2>/dev/null || echo "Domain NS belum tersedia")
domain=$(cat /etc/xray/domain 2>/dev/null || hostname -f)

uuid=$(cat /proc/sys/kernel/random/uuid)
password=$(openssl rand -base64 16)

if [ ! -d "/etc/xray/shadowsocks" ]; then
    echo -e "${yellow}Direktori /etc/xray/shadowsocks tidak ditemukan. Membuat direktori...${reset}"

    mkdir -p /etc/xray/shadowsocks

    if [ $? -ne 0 ]; then
        echo -e "${red}Gagal membuat direktori /etc/xray/shadowsocks.${reset}"
        exit 1
    fi
fi

if [ ! -f "/etc/xray/shadowsocks/config.json" ]; then
    echo -e "${yellow}Konfigurasi Shadowsocks tidak ditemukan. Membuat konfigurasi baru...${reset}"

    echo '{"inbounds": []}' >/etc/xray/shadowsocks/config.json
fi

echo ""
echo -ne "${yellow}Menyiapkan Akun Premium${reset}"

for i in {1..2}; do
    for j in ⠋ ⠙ ⠹ ⠸ ⠼ ⠴ ⠦ ⠧ ⠇ ⠏; do
        echo -ne "\r${yellow}Menyiapkan Akun Premium $j${reset}"
        sleep 0.1
    done
done

echo -ne "\r${green}Akun Premium siap dibuat!${reset}\n"

sleep 1

clear

box_top
box_center "INTERFLAZZ.MY.ID" "$green"
box_center "BUAT AKUN SHADOWSOCKS" "$bold_white"
box_middle
box_center "MASUKKAN DATA PENGGUNA" "$yellow"
box_bottom

echo ""

while true; do
    read -p "Nama Pengguna : " user

    if [[ ${#user} -lt 3 || ! "$user" =~ ^[a-zA-Z0-9_-]+$ ]]; then
        echo -e "${red}Nama pengguna minimal 3 karakter dan hanya boleh berisi huruf, angka, _ atau -.${reset}"
        continue
    fi

    if grep -q "^### $user " /etc/xray/shadowsocks/config.json; then
        random_number=$(head /dev/urandom | tr -dc A-Za-z0-9 | head -c 5)

        user="${random_number}${user}"

        echo -e "${yellow}Nama pengguna sudah tersedia. Nama baru digunakan: $user${reset}"

        break
    else
        break
    fi
done

echo ""

clear

box_top
box_center "INTERFLAZZ.MY.ID" "$green"
box_center "XRAY / SHADOWSOCKS" "$bold_white"
box_middle
box_left "Nama Pengguna : $user" "$white"
box_middle
box_left "Masukkan masa aktif akun dalam hari." "$yellow"
box_left "Masukkan batas kuota dalam GB." "$yellow"
box_left "Masukkan batas jumlah IP." "$yellow"
box_left "Gunakan angka 0 untuk tanpa batas." "$green"
box_bottom

echo ""

until [[ $duration =~ ^[0-9]+$ ]]; do
    read -p "Masa Aktif (Hari) : " duration

    if [[ ! $duration =~ ^[0-9]+$ ]]; then
        echo -e "${red}Masa aktif harus berupa angka.${reset}"
    fi
done

until [[ $quota =~ ^[0-9]+$ ]]; do
    read -p "Batas Kuota (GB) : " quota

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

until [[ $ip_limit =~ ^[0-9]+$ ]]; do
    read -p "Batas IP : " ip_limit

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

exp=$(date -d "$duration days" +"%Y-%m-%d")

method="aes-256-gcm"

password=$(cat /proc/sys/kernel/random/uuid)

sed -i '/#ssws$/a\### '"$user $exp"'\
},{"password": "'""$password""'","method": "'""$method""'","email": "'""$user""'"' /etc/xray/shadowsocks/config.json

sed -i '/#ssgrpc$/a\### '"$user $exp"'\
},{"password": "'""$password""'","method": "'""$method""'","email": "'""$user""'"' /etc/xray/shadowsocks/config.json

ss_base64=$(echo -n "${method}:${password}" | base64 -w 0)

ss_link_ws="ss://${ss_base64}@${domain}:443?plugin=xray-plugin;mux=0;path=/ss-ws;host=${domain};tls;network=ws;host=$domain#${user}-WS"

ss_link_grpc="ss://${ss_base64}@${domain}:443?plugin=xray-plugin;mux=0;serviceName=ss-grpc;host=${domain};tls#${user}-gRPC"

cat >/var/www/html/shadowsocks-$user.txt <<END
────────────────────────────────────────
SHADOWSOCKS WS FORMAT
────────────────────────────────────────

{
 "dns": {
    "servers": [
      "8.8.8.8",
      "8.8.4.4"
    ]
  },
 "inbounds": [
   {
      "port": 10808,
      "protocol": "socks",
      "settings": {
        "auth": "noauth",
        "udp": true,
        "userLevel": 8
      },
      "sniffing": {
        "destOverride": [
          "http",
          "tls"
        ],
        "enabled": true
      },
      "tag": "socks"
    },
    {
      "port": 10809,
      "protocol": "http",
      "settings": {
        "userLevel": 8
      },
      "tag": "http"
    }
  ],
  "log": {
    "loglevel": "none"
  },
  "outbounds": [
    {
      "mux": {
        "enabled": true
      },
      "protocol": "shadowsocks",
      "settings": {
        "servers": [
          {
            "address": "$domain",
            "level": 8,
            "method": "$method",
            "password": "$uuid",
            "port": 443
          }
        ]
      },
      "streamSettings": {
        "network": "ws",
        "security": "tls",
        "tlsSettings": {
          "allowInsecure": true,
          "serverName": "$domain"
        },
        "wsSettings": {
          "headers": {
            "Host": "$domain"
          },
          "path": "/whatever/ss-ws"
        }
      },
      "tag": "proxy"
    },
    {
      "protocol": "freedom",
      "settings": {},
      "tag": "direct"
    },
    {
      "protocol": "blackhole",
      "settings": {
        "response": {
          "type": "http"
        }
      },
      "tag": "block"
    }
  ],
  "policy": {
    "levels": {
      "8": {
        "connIdle": 300,
        "downlinkOnly": 1,
        "handshake": 4,
        "uplinkOnly": 1
      }
    },
    "system": {
      "statsOutboundUplink": true,
      "statsOutboundDownlink": true
    }
  },
  "routing": {
    "domainStrategy": "Asls",
    "rules": []
  },
  "stats": {}
}

────────────────────────────────────────
SHADOWSOCKS GRPC FORMAT
────────────────────────────────────────

{
  "dns": {
    "servers": [
      "8.8.8.8",
      "8.8.4.4"
    ]
  },
  "inbounds": [
    {
      "port": 10808,
      "protocol": "socks",
      "settings": {
        "auth": "noauth",
        "udp": true,
        "userLevel": 8
      },
      "sniffing": {
        "destOverride": [
          "http",
          "tls"
        ],
        "enabled": true
      },
      "tag": "socks"
    },
    {
      "port": 10809,
      "protocol": "http",
      "settings": {
        "userLevel": 8
      },
      "tag": "http"
    }
  ],
  "log": {
    "loglevel": "none"
  },
  "outbounds": [
    {
      "mux": {
        "enabled": true
      },
      "protocol": "shadowsocks",
      "settings": {
        "servers": [
          {
            "address": "$domain",
            "level": 8,
            "method": "$method",
            "password": "$uuid",
            "port": 443
          }
        ]
      },
      "streamSettings": {
        "grpcSettings": {
          "multiMode": true,
          "serviceName": "ss-grpc"
        },
        "network": "grpc",
        "security": "tls",
        "tlsSettings": {
          "allowInsecure": true,
          "serverName": "$domain"
        }
      },
      "tag": "proxy"
    },
    {
      "protocol": "freedom",
      "settings": {},
      "tag": "direct"
    },
    {
      "protocol": "blackhole",
      "settings": {
        "response": {
          "type": "http"
        }
      },
      "tag": "block"
    }
  ],
  "policy": {
    "levels": {
      "8": {
        "connIdle": 300,
        "downlinkOnly": 1,
        "handshake": 4,
        "uplinkOnly": 1
      }
    },
    "system": {
      "statsOutboundUplink": true,
      "statsOutboundDownlink": true
    }
  },
  "routing": {
    "domainStrategy": "Asls",
    "rules": []
  },
  "stats": {}
}

────────────────────────────────────────
LINK AKUN SHADOWSOCKS
────────────────────────────────────────

SS WS Link
${ss_link_ws}

────────────────────────────────────────

SS gRPC Link
${ss_link_grpc}

────────────────────────────────────────
INTERFLAZZ.MY.ID
────────────────────────────────────────

END

if ! systemctl restart shadowsocks@config >/dev/null 2>&1; then
    echo ""

    box_top
    box_center "INTERFLAZZ.MY.ID" "$green"
    box_middle
    box_center "GAGAL MEMULAI ULANG SHADOWSOCKS" "$red"
    box_middle
    box_left "Silakan periksa konfigurasi dan log systemd." "$yellow"
    box_bottom

    exit 1
fi

if [ ! -f "/etc/xray/shadowsocks/config.json" ]; then
    echo -e "${yellow}Konfigurasi Shadowsocks tidak ditemukan. Membuat file baru...${reset}"

    mkdir -p /etc/xray/shadowsocks

    echo '{"server":["::1", "0.0.0.0"],"mode":"tcp_and_udp"}' >/etc/xray/shadowsocks/config.json

    systemctl restart shadowsocks@config
fi

if [ ! -d "/etc/xray/shadowsocks" ]; then
    echo -e "${yellow}Direktori /etc/xray/shadowsocks tidak ditemukan. Membuat direktori...${reset}"

    mkdir -p /etc/xray/shadowsocks

    if [ $? -ne 0 ]; then
        echo -e "${red}Gagal membuat direktori /etc/xray/shadowsocks. Pastikan izin akses mencukupi.${reset}"
        exit 1
    fi
fi

[ -z "${ip_limit:-}" ] && ip_limit="0"
[ -z "${quota:-}" ] && quota="0"

quota_bytes=$((${quota} * 1024 * 1024 * 1024))

if [[ ${quota} != "0" ]]; then
    echo "${quota_bytes}" >/etc/xray/shadowsocks/${user}
    echo "${ip_limit}" >/etc/xray/shadowsocks/${user}IP
fi

db_file="/etc/xray/shadowsocks/.shadowsocks.db"
temp_file="/etc/xray/shadowsocks/.shadowsocks.db.tmp"

if [ ! -f "$db_file" ]; then
    echo -e "${yellow}Database Shadowsocks tidak ditemukan. Membuat database baru...${reset}"

    touch "$db_file"
fi

grep -v "^### ${user} " "$db_file" >"$temp_file"
mv "$temp_file" "$db_file"

echo "### ${user} ${exp} ${password}" >>"$db_file"

clear -x

box_top
box_center "INTERFLAZZ.MY.ID" "$green"
box_center "AKUN XRAY / SHADOWSOCKS" "$bold_white"
box_middle
box_left "Nama Pengguna : ${user}" "$white"
box_left "Server         : ${domain}" "$white"
box_left "XrayDNS        : ${ns_domain}" "$white"
box_left "Lokasi         : ${city}" "$white"
box_left "Port           : 443" "$white"
box_left "Metode         : ${method}" "$white"
box_left "Password       : ${password}" "$white"
box_left "Path WS        : /whatever/ss-ws" "$white"
box_left "Service Name   : ss-grpc" "$white"
box_left "Public Key     : ${pubkey}" "$white"
box_middle
box_left "Batas IP       : ${ip_limit}" "$yellow"
box_left "Kuota          : ${quota} GB" "$yellow"
box_left "Masa Aktif     : ${duration} Hari" "$yellow"
box_left "Kadaluarsa    : ${exp}" "$yellow"
box_middle
box_left "SS WS Link :" "$green"
box_left "${ss_link_ws}" "$white"
box_middle
box_left "SS gRPC Link :" "$green"
box_left "${ss_link_grpc}" "$white"
box_middle
box_left "Format OpenClash :" "$cyan"
box_left "https://${domain}:81/shadowsocks-${user}.txt" "$white"
box_middle
box_left "WhatsApp ~ https://wa.me/6285956131443" "$green"
box_left "Telegram ~ https://t.me/interflazz" "$cyan"
box_bottom

{
    echo "────────────────────────────────────────────"
    echo "INTERFLAZZ.MY.ID"
    echo "AKUN XRAY / SHADOWSOCKS"
    echo "────────────────────────────────────────────"
    echo "Nama Pengguna : ${user}"
    echo "Server         : ${domain}"
    echo "XrayDNS        : ${ns_domain}"
    echo "Lokasi         : ${city}"
    echo "Port           : 443"
    echo "Metode         : ${method}"
    echo "Password       : ${password}"
    echo "Path WS        : /whatever/ss-ws"
    echo "Service Name   : ss-grpc"
    echo "Public Key     : ${pubkey}"
    echo "Batas IP       : ${ip_limit}"
    echo "Kuota          : ${quota} GB"
    echo "Masa Aktif     : ${duration} Hari"
    echo "Kadaluarsa    : ${exp}"
    echo "────────────────────────────────────────────"
    echo "SS WS Link"
    echo "${ss_link_ws}"
    echo "────────────────────────────────────────────"
    echo "SS gRPC Link"
    echo "${ss_link_grpc}"
    echo "────────────────────────────────────────────"
    echo "Format OpenClash"
    echo "https://${domain}:81/shadowsocks-${user}.txt"
    echo "────────────────────────────────────────────"
    echo "WhatsApp ~ https://wa.me/6285956131443"
    echo "Telegram ~ https://t.me/interflazz"
    echo "────────────────────────────────────────────"
    echo ""
} >>"/etc/xray/shadowsocks/log-create-${user}.log"