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

BASE_DIR="/etc/xray/shadowsocks"
CONFIG_FILE="${BASE_DIR}/config.json"
DB_FILE="${BASE_DIR}/.shadowsocks.db"
USAGE_DIR="${BASE_DIR}/usage"
WEB_DIR="/var/www/html"

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
}

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

generate_username() {
    local generated

    while true; do
        generated=$(
            tr -dc 'a-z0-9' </dev/urandom |
                head -c 8
        )

        [ -z "$generated" ] && continue

        if ! grep -q "^### ${generated} " "$DB_FILE" 2>/dev/null; then
            printf '%s' "$generated"
            return
        fi
    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))

mkdir -p "$BASE_DIR" "$USAGE_DIR" "$WEB_DIR"

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

if [ ! -f "$CONFIG_FILE" ]; then
    clear

    box_top
    box_center "$BRAND" "$green"
    box_center "TRIAL SHADOWSOCKS" "$bold_white"
    box_middle
    box_center "CONFIG TIDAK DITEMUKAN" "$red"
    box_middle
    box_left "File : $CONFIG_FILE" "$yellow"
    box_bottom

    exit 1
fi

if ! grep -q '^#ssws$' "$CONFIG_FILE"; then
    clear

    box_top
    box_center "$BRAND" "$green"
    box_center "TRIAL SHADOWSOCKS" "$bold_white"
    box_middle
    box_center "MARKER CONFIG TIDAK DITEMUKAN" "$red"
    box_middle
    box_left "Marker : #ssws" "$yellow"
    box_bottom

    exit 1
fi

if ! grep -q '^#ssgrpc$' "$CONFIG_FILE"; then
    clear

    box_top
    box_center "$BRAND" "$green"
    box_center "TRIAL SHADOWSOCKS" "$bold_white"
    box_middle
    box_center "MARKER CONFIG TIDAK DITEMUKAN" "$red"
    box_middle
    box_left "Marker : #ssgrpc" "$yellow"
    box_bottom

    exit 1
fi

domain=$(cat /etc/xray/domain 2>/dev/null)
city=$(cat /etc/xray/city 2>/dev/null)
pubkey=$(cat /etc/slowdns/server.pub 2>/dev/null)
ns_domain=$(cat /etc/xray/dns 2>/dev/null)

domain=${domain:-$(hostname -f 2>/dev/null)}
city=${city:-Tidak diketahui}
pubkey=${pubkey:-Tidak tersedia}
ns_domain=${ns_domain:-Belum diatur}

if [ -z "$domain" ]; then
    echo -e "${red}Domain VPS belum dikonfigurasi.${reset}"
    exit 1
fi

clear

box_top
box_center "$BRAND" "$green"
box_center "BUAT TRIAL SHADOWSOCKS" "$bold_white"
box_middle
box_center "MEMPERSIAPKAN AKUN TRIAL" "$yellow"
box_bottom

echo ""

for i in 1 2; do
    for spinner in "⠋" "⠙" "⠹" "⠸" "⠼" "⠴" "⠦" "⠧" "⠇" "⠏"; do
        printf "\r%bMenyiapkan akun trial %s%b" "$yellow" "$spinner" "$reset"
        sleep 0.1
    done
done

printf "\r%bAkun trial siap dibuat.            %b\n" "$green" "$reset"
sleep 1

clear

box_top
box_center "$BRAND" "$green"
box_center "TRIAL SHADOWSOCKS" "$bold_white"
box_middle
box_center "MASUKKAN DURASI TRIAL" "$yellow"
box_bottom

echo ""

user=$(generate_username)

echo -e "Username otomatis : ${green}${user}${reset}"

while true; do
    read -rp "Durasi trial [menit] : " duration

    if [[ "$duration" =~ ^[1-9][0-9]*$ ]]; then
        break
    fi

    echo -e "${red}Durasi trial harus berupa angka lebih dari 0 menit.${reset}"
done

method="aes-256-gcm"
password=$(cat /proc/sys/kernel/random/uuid)

expiry_days=$(((duration + 1439) / 1440))

if [ "$expiry_days" -lt 1 ]; then
    expiry_days=1
fi

exp=$(date -d "+${expiry_days} days" +"%Y-%m-%d")

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

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

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

printf '0\n' >"${USAGE_DIR}/${user}"
printf '0\n' >"${BASE_DIR}/${user}"
printf '0\n' >"${BASE_DIR}/${user}IP"

ss_base64=$(
    printf '%s' "${method}:${password}" |
        base64 -w 0
)

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

cat >"${WEB_DIR}/shadowsocks-${user}.txt" <<EOF
========================================
${BRAND}
SHADOWSOCKS TRIAL ACCOUNT
========================================

Username    : ${user}
Domain      : ${domain}
Port        : 443
Method      : ${method}
Password    : ${password}
Path WS     : /whatever/ss-ws
ServiceName : ss-grpc
Durasi      : ${duration} Menit

========================================
SHADOWSOCKS WEBSOCKET CONFIG
========================================

{
  "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": "${password}",
            "port": 443
          }
        ]
      },
      "streamSettings": {
        "network": "ws",
        "security": "tls",
        "tlsSettings": {
          "allowInsecure": false,
          "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": "AsIs",
    "rules": []
  },
  "stats": {}
}

========================================
SHADOWSOCKS GRPC CONFIG
========================================

{
  "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": "${password}",
            "port": 443
          }
        ]
      },
      "streamSettings": {
        "network": "grpc",
        "security": "tls",
        "tlsSettings": {
          "allowInsecure": false,
          "serverName": "${domain}"
        },
        "grpcSettings": {
          "multiMode": true,
          "serviceName": "ss-grpc"
        }
      },
      "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": "AsIs",
    "rules": []
  },
  "stats": {}
}

========================================
LINK AKUN
========================================

WS:
${ss_link_ws}

gRPC:
${ss_link_grpc}

========================================
EOF

if ! systemctl restart shadowsocks@config >/dev/null 2>&1; then
    sed -i "/^### ${user} ${exp}$/,+1d" "$CONFIG_FILE"
    sed -i "/^### ${user} /d" "$DB_FILE"

    rm -f \
        "${BASE_DIR}/${user}" \
        "${BASE_DIR}/${user}IP" \
        "${USAGE_DIR}/${user}" \
        "${WEB_DIR}/shadowsocks-${user}.txt"

    clear

    box_top
    box_center "$BRAND" "$green"
    box_center "GAGAL MEMBUAT TRIAL" "$red"
    box_middle
    box_center "Service Shadowsocks gagal direstart." "$yellow"
    box_bottom

    exit 1
fi

if ! command -v trial >/dev/null 2>&1; then
    sed -i "/^### ${user} ${exp}$/,+1d" "$CONFIG_FILE"
    sed -i "/^### ${user} /d" "$DB_FILE"

    rm -f \
        "${BASE_DIR}/${user}" \
        "${BASE_DIR}/${user}IP" \
        "${USAGE_DIR}/${user}" \
        "${WEB_DIR}/shadowsocks-${user}.txt"

    systemctl restart shadowsocks@config >/dev/null 2>&1

    clear

    box_top
    box_center "$BRAND" "$green"
    box_center "GAGAL MEMBUAT TRIAL" "$red"
    box_middle
    box_center "Command trial tidak ditemukan." "$yellow"
    box_bottom

    exit 1
fi

if command -v tmux >/dev/null 2>&1; then
    tmux kill-session -t "trial_shadowsocks_${user}" >/dev/null 2>&1 || true

    tmux new-session \
        -d \
        -s "trial_shadowsocks_${user}" \
        "trial trialss '${user}' '${duration}'"
else
    nohup trial trialss "$user" "$duration" \
        >/dev/null 2>&1 &
fi

clear

box_top
box_center "$BRAND" "$green"
box_center "TRIAL SHADOWSOCKS BERHASIL" "$bold_white"
box_middle
box_left "Username    : $user" "$white"
box_left "Host Server : $domain" "$white"
box_left "Xray DNS    : $ns_domain" "$white"
box_left "Lokasi      : $city" "$white"
box_left "Port TLS    : 443" "$white"
box_left "Metode      : $method" "$white"
box_left "Password    : $password" "$white"
box_left "Path WS     : /whatever/ss-ws" "$white"
box_left "ServiceName : ss-grpc" "$white"
box_left "Public Key  : $pubkey" "$white"
box_middle
box_left "Durasi Trial: $duration Menit" "$yellow"
box_left "Kadaluarsa  : Otomatis setelah $duration menit" "$yellow"
box_bottom

echo ""

box_top
box_center "SHADOWSOCKS WEBSOCKET" "$bold_white"
box_middle
box_left "$ss_link_ws" "$green"
box_bottom

echo ""

box_top
box_center "SHADOWSOCKS GRPC" "$bold_white"
box_middle
box_left "$ss_link_grpc" "$green"
box_bottom

echo ""

box_top
box_center "OPENCLASH CONFIG" "$bold_white"
box_middle
box_left "https://${domain}:81/shadowsocks-${user}.txt" "$cyan"
box_bottom

echo ""

box_top
box_center "INFORMASI SCRIPT" "$bold_white"
box_middle
box_left "Masa Aktif Script : $remaining_days Hari" "$yellow"
box_left "WhatsApp ~ $WHATSAPP" "$green"
box_left "Telegram ~ $TELEGRAM" "$cyan"
box_bottom

exit 0