#!/bin/bash
clear

# Mengambil nilai domain dan token dari file
domain=$(cat /root/domain)
get_marzban_api_port() {
  local env_file="/opt/marzban/.env"
  [[ -r "$env_file" ]] || { echo "7879"; return; }   # fallback opsional

  local port
  port="$(grep -E '^[[:space:]]*UVICORN_PORT[[:space:]]*=' "$env_file" \
           | tail -n1 \
           | sed -E 's/.*=[[:space:]]*["'\'']?([0-9]+).*/\1/')"

  # Validasi angka
  if [[ "$port" =~ ^[0-9]+$ ]]; then
    echo "$port"
  else
    echo "7879"   # fallback opsional lain
  fi
}

api_port="$(get_marzban_api_port)"

# Meminta input pengguna
while true; do
    read -rp "Username: " -e user

    # Validasi panjang karakter
    if [[ ${#user} -lt 4 || ${#user} -gt 32 ]]; then
        echo "Username harus memiliki panjang minimal 4 karakter dan maksimal 32 karakter."
        continue
    fi

    # Validasi karakter tanpa spesial karakter
    if [[ ! "$user" =~ ^[a-zA-Z0-9_]+$ ]]; then
        echo "Username hanya dapat mengandung huruf, angka, dan underscore (_) tanpa karakter spesial."
        continue
    fi

    TOTAL_USERS=$(curl -s -X 'GET' \
        "https://${domain}/api/users?username=${user}" \
        -H 'accept: application/json' \
        -H "Authorization: Bearer ${token}" \
        | jq -r '.total')

    if [[ ${TOTAL_USERS} == '1' ]]; then
        echo ""
        echo "Klien dengan username ${user} sudah terdaftar pada database, mohon gunakan username lain."
        exit 1
    fi

    # Jika semua validasi terpenuhi, keluar dari loop
    break
done

read -rp "Catatan user: " -e catatan
echo "Masa aktif"
echo "[biarkan kosong atau tekan saja enter jika tidak butuh masa aktif / AlwaysON]"
read -p "Expired (Hari): " masaaktif
echo "[biarkan kosong atau tekan saja enter jika ingin sett Unlimited Quota]"
read -rp "Quota (GB): " -e gb

if [ -n "$gb" ]; then
    limitq=$((gb * 1024**3))
    quota_text="${gb} GB"

# Menampilkan opsi reset data
echo "Pilih jenis siklus reset data:"
echo "1. Tanpa ada reset"
echo "2. Harian"
echo "3. Mingguan"
echo "4. Bulanan"
echo "5. Tahunan"

# Menerima input pilihan pengguna
read -p "Masukkan nomor pilihan Anda: " choice

# Memilih strategi reset berdasarkan pilihan pengguna
case $choice in
    1)
        reset_strategy="no_reset"
        ;;
    2)
        reset_strategy="day"
        ;;
    3)
        reset_strategy="week"
        ;;
    4)
        reset_strategy="month"
        ;;
    5)
        reset_strategy="year"
        ;;
    *)
        echo "Pilihan tidak valid."
        exit 1
        ;;
esac
    
else
    limitq=0
    quota_text="Unlimited"
    reset_strategy="no_reset"
fi

# Menggunakan variable uuid untuk generate password
uuid=$(cat /proc/sys/kernel/random/uuid)

if [ -n "$masaaktif" ]; then
    exp=$((masaaktif * 24 * 60 * 60))
    exp2=$(date -d "${masaaktif} days" +"%Y-%m-%d")
    exp3=$(date -d "+14 days" +"%Y-%m-%dT%H:%M:%S")
    text="${masaaktif} Hari"
    text2="Masa OnHold: 14 Hari [${exp3}]"

# Mengirimkan permintaan ke API
curl -X 'POST' \
  "https://${domain}/api/user" \
  -H 'accept: application/json' \
  -H "Authorization: Bearer ${token}" \
  -H 'Content-Type: application/json' \
  -d '{
  "username": "'"${user}"'",
  "proxies": {
    "vmess": {
      "id": "'"${uuid}"'"
    }
  },
  "inbounds": {
    "vmess": [
      "VMESS_TCP"
    ]
  },
  "data_limit": '"${limitq}"',
  "data_limit_reset_strategy": "'"${reset_strategy}"'",
  "status": "on_hold",
  "note": "'"${catatan}"'",
  "on_hold_timeout": "'"${exp3}"'",
  "on_hold_expire_duration": '"${exp}"'
}' > /tmp/${user}_vmess.json
else
    exp=0
    exp2="AlwaysON"
    exp3="AlwaysON"
    text="AlwaysON"
    text2="Tidak berlaku OnHOLD"

# Mengirimkan permintaan ke API
curl -X 'POST' \
  "https://${domain}/api/user" \
  -H 'accept: application/json' \
  -H "Authorization: Bearer ${token}" \
  -H 'Content-Type: application/json' \
  -d '{
  "username": "'"${user}"'",
  "proxies": {
    "vmess": {
      "id": "'"${uuid}"'"
    }
  },
  "inbounds": {
    "vmess": [
      "VMESS_TCP"
    ]
  },
  "expire": '"${exp}"',
  "data_limit": '"${limitq}"',
  "data_limit_reset_strategy": "'"${reset_strategy}"'",
  "status": "active",
  "note": "'"${catatan}"'"
}' > /tmp/${user}_vmess.json
fi
subs=$(cat /tmp/${user}_vmess.json | jq -r .subscription_url)

# Link VMess
tcp1=`cat<<EOF
      {
      "v": "2",
      "ps": "(${user}) [VMess - TCP] TLS",
      "add": "${domain}",
      "port": "443",
      "id": "${uuid}",
      "aid": "0",
      "net": "tcp",
      "path": "/vmess-tcp",
      "type": "http",
      "host": "",
      "tls": "tls"
}
EOF`
tcp2=`cat<<EOF
      {
      "v": "2",
      "ps": "(${user}) [VMess - TCP] nonTLS",
      "add": "${domain}",
      "port": "80",
      "id": "${uuid}",
      "aid": "0",
      "net": "tcp",
      "path": "/vmess-tcp",
      "type": "http",
      "host": "",
      "tls": "none"
}
EOF`
vmesslink1="vmess://$(echo $tcp1 | base64 -w 0)"
vmesslink2="vmess://$(echo $tcp2 | base64 -w 0)"

# Contoh Format Openclash
echo "==--LINGVPN PRESENTS--==
TERIMA KASIH TELAH MEMILIH LAYANAN VPN LINGVPN!
LINK URL/CONFIG UNTUK USER ${user^^} DENGAN KUOTA ${quota_text} dan MASA AKTIF ${text}
MOHON MELAKUKAN PERPANJANGAN VPN MAKSMIMAL 3 HARI SEBELUM TANGGAL EXPIRED SETIAP BULAN NYA!

DETAIL Keterangan ALPN (HARUS DI SETT!):
1.) TCP: http/1.1

DETAIL Port Server (Pilih salah satu, Sesuaikan dengan bug masing masing):
1.) TLS : 443, 8443, 8880
2.) HTTP/nonTLS : 80, 2082, 2083, 3128, 8080

DETAIL AKUN lain lain, WebSocket, FLOW, serverName Reality dan serviceName GRPC:

🔑 VMess
a.) path TCP Header: /vmess-tcp

Config URL :

-==============================-

1.) Vmess-TCP TLS
${vmesslink1}

2.) Vmess-TCP nonTLS
${vmesslink2}

-==============================-

Format Openclash : 

VMESS TCP TIDAK SUPPORT DI OPENCLASH :(
UNTUK USER OPENWRT GUNAKAN PASSWALL/PASSWALL2 YA~

SELALU PATUHI PERATURAN SERVER DAN TERIMA KASIH SUDAH MEMILIH LINGVPN 🙏

CONTACT WA : https://wa.me/6283129611215
TELEGRAM CHANNEL : https://t.me/LingVPN
TELEGRAM GROUP : https://t.me/LingVPN_Group" > "/var/www/html/oc-${user}.conf"
clear
echo -e "=======-XRAY/VMESS-TCP======="
echo -e ""
echo -e "Remarks: ${user}"
echo -e "Domain: ${domain}"
echo -e "Quota: ${quota_text}"
# Replace values and specific reset strategies
  case "${reset_strategy}" in
    "no_reset") reset_strategy="Loss_doll";;
    "day") reset_strategy="Harian";;
    "week") reset_strategy="Mingguan";;
    "month") reset_strategy="Bulanan";;
    "year") reset_strategy="Tahunan";;
esac
echo -e "Reset Quota Strategy: ${reset_strategy}"
echo -e "================================="
echo -e "🔑 Port TLS: 443, 8443, 8880"
echo -e "🔑 Port nonTLS: 80, 2082, 2083, 3128, 8080"
echo -e "================================="
echo -e "id: ${uuid}"
echo -e "alterID: 0"
echo -e "security: auto"
echo -e "================================="
echo -e "network: tcp"
echo -e "head type: http"
echo -e "path http: /vmess-tcp"
echo -e "================================="
echo -e "alpn: http/1.1"
echo -e "tls:"
echo -e "true (tls) atau false (nontls)"
echo -e "allowInsecure: true"
echo -e "================================="
echo -e "Link config: https://${domain}/oc-${user}.conf"
echo -e "================================="
echo -e "Link Subscription : https://${domain}${subs}"
echo -e "================================="
echo -e "Masa Aktif: ${text}"
echo -e "${text2}"
rm -r /tmp/${user}_vmess.json