#!/bin/bash

rm -rf /root/install.sh

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

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"

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" "$neutral"
}

box_middle() {
    update_box_width

    printf "%b├" "$orange"
    repeat_char $((BOX_WIDTH - 2)) "─"
    printf "┤%b\n" "$neutral"
}

box_bottom() {
    update_box_width

    printf "%b└" "$orange"
    repeat_char $((BOX_WIDTH - 2)) "─"
    printf "┘%b\n" "$neutral"
}

box_center() {
    update_box_width

    local text="$1"
    local color="${2:-$neutral}"
    local length=${#text}
    local available="$BOX_INNER"

    if [ "$length" -gt "$available" ]; then
        printf "%b│%b %b%s%b %b│%b\n" \
            "$orange" \
            "$neutral" \
            "$color" \
            "$text" \
            "$neutral" \
            "$orange" \
            "$neutral"
        return
    fi

    local left=$(((available - length) / 2))
    local right=$((available - length - left))

    printf "%b│%b " "$orange" "$neutral"
    printf "%*s" "$left" ""
    printf "%b%s%b" "$color" "$text" "$neutral"
    printf "%*s" "$right" ""
    printf " %b│%b\n" "$orange" "$neutral"
}

box_left() {
    update_box_width

    local text="$1"
    local color="${2:-$neutral}"
    local length=${#text}
    local available="$BOX_INNER"

    if [ "$length" -gt "$available" ]; then
        printf "%b│%b %b%s%b %b│%b\n" \
            "$orange" \
            "$neutral" \
            "$color" \
            "$text" \
            "$neutral" \
            "$orange" \
            "$neutral"
        return
    fi

    local right=$((available - length))

    printf "%b│%b " "$orange" "$neutral"
    printf "%b%s%b" "$color" "$text" "$neutral"
    printf "%*s" "$right" ""
    printf " %b│%b\n" "$orange" "$neutral"
}

print_rainbow() {
    local text="$1"
    local length=${#text}
    local start_color=(0 5 0)
    local mid_color=(0 200 0)
    local end_color=(0 5 0)

    if [ "$length" -le 1 ]; then
        echo -e "$text"
        return
    fi

    for ((i = 0; i < length; i++)); do
        local progress=$((i * 100 / (length - 1)))

        if [ $progress -lt 50 ]; then
            local factor=$((progress * 2))
            r=$(((start_color[0] * (100 - factor) + mid_color[0] * factor) / 100))
            g=$(((start_color[1] * (100 - factor) + mid_color[1] * factor) / 100))
            b=$(((start_color[2] * (100 - factor) + mid_color[2] * factor) / 100))
        else
            local factor=$(((progress - 50) * 2))
            r=$(((mid_color[0] * (100 - factor) + end_color[0] * factor) / 100))
            g=$(((mid_color[1] * (100 - factor) + end_color[1] * factor) / 100))
            b=$(((mid_color[2] * (100 - factor) + end_color[2] * factor) / 100))
        fi

        printf "\e[38;2;%d;%d;%dm%s" "$r" "$g" "$b" "${text:$i:1}"
    done

    echo -e "$reset"
}

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
    clear

    box_top
    box_center "INTERFLAZZ.MY.ID" "$green"
    box_middle
    box_center "AKSES DITOLAK!" "$red"
    box_center "IP VPS Anda: $vps_ip" "$yellow"
    box_center "VPS belum memiliki izin akses script." "$yellow"
    box_middle
    box_center "HUBUNGI ADMIN" "$bold_white"
    box_center "WhatsApp ~ https://wa.me/6285956131443" "$green"
    box_center "Telegram ~ https://t.me/interflazz" "$blue"
    box_bottom

    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
    clear

    box_top
    box_center "INTERFLAZZ.MY.ID" "$green"
    box_middle
    box_center "AKSES DITOLAK!" "$red"
    box_center "IP VPS Anda: $vps_ip" "$yellow"
    box_center "Masa aktif akses script telah berakhir." "$yellow"
    box_middle
    box_center "HUBUNGI ADMIN" "$bold_white"
    box_center "WhatsApp ~ https://wa.me/6285956131443" "$green"
    box_center "Telegram ~ https://t.me/interflazz" "$blue"
    box_bottom

    exit 1
fi

domain_ns="vpnnode.biz.id"
cf_id="deltanevaangkasa@gmail.com"
cf_key="cfk_pbgN0TujS8Vcv0RtHkNLuzkqcT98FEKBfkxLdOpKc34c90c7"

directories=(
    /etc/xray
    /etc/vmess
    /etc/vless
    /etc/trojan
    /etc/shadowsocks
    /usr/bin/xray
    /var/log/xray
    /var/www/html
    /etc/haproxy
    /etc/xray/vmess
    /etc/xray/vless
    /etc/xray/trojan
    /etc/xray/shadowsocks
    /etc/xray/ssh
)

for dir in "${directories[@]}"; do
    [ ! -d "$dir" ] && mkdir -p "$dir"
    chmod 777 "$dir"
done

clear

if [ -z "$1" ]; then
    box_top
    box_center "INTERFLAZZ.MY.ID" "$green"
    box_center "AUTOSCRIPT PREMIUM" "$bold_white"
    box_middle
    box_center "Koneksi Aman, Cepat, Stabil dan Terbaik!" "$blue"
    box_middle
    box_left "1) Gunakan Domain Sendiri" "$yellow"
    box_left "2) Gunakan Domain Acak dari Server" "$yellow"
    box_bottom

    echo ""
    read -p "Pilih [1-2]: " pilih_domain
    echo ""

    if [[ $pilih_domain == "1" ]]; then
        read -p "Masukkan domain Anda: " domain

        echo "$domain" >/etc/xray/domain

    elif [[ $pilih_domain == "2" ]]; then
        sub=$(tr </dev/urandom -dc a-z0-9 | head -c7)

        domain="$sub.$domain_ns"

        echo "$domain" >/etc/xray/domain

        zone=$(
            curl -sLX GET \
                "https://api.cloudflare.com/client/v4/zones?name=${domain_ns}&status=active" \
                -H "X-Auth-Email: ${cf_id}" \
                -H "X-Auth-Key: ${cf_key}" \
                -H "Content-Type: application/json" |
                jq -r .result[0].id
        )

        curl -sLX POST \
            "https://api.cloudflare.com/client/v4/zones/${zone}/dns_records" \
            -H "X-Auth-Email: ${cf_id}" \
            -H "X-Auth-Key: ${cf_key}" \
            -H "Content-Type: application/json" \
            --data '{"type":"A","name":"'${domain}'","content":"'${vps_ip}'","proxied":false}' \
            >/dev/null 2>&1

        echo ""

        box_top
        box_center "DOMAIN BERHASIL DIBUAT" "$green"
        box_middle
        box_left "Subdomain: $domain" "$green"
        box_bottom

        sleep 2

    else
        echo -e "${red}Pilihan tidak valid, menggunakan subdomain acak...${neutral}"

        sub=$(tr </dev/urandom -dc a-z0-9 | head -c7)

        domain="$sub.$domain_ns"

        echo "$domain" >/etc/xray/domain

        zone=$(
            curl -sLX GET \
                "https://api.cloudflare.com/client/v4/zones?name=${domain_ns}&status=active" \
                -H "X-Auth-Email: ${cf_id}" \
                -H "X-Auth-Key: ${cf_key}" \
                -H "Content-Type: application/json" |
                jq -r .result[0].id
        )

        curl -sLX POST \
            "https://api.cloudflare.com/client/v4/zones/${zone}/dns_records" \
            -H "X-Auth-Email: ${cf_id}" \
            -H "X-Auth-Key: ${cf_key}" \
            -H "Content-Type: application/json" \
            --data '{"type":"A","name":"'${domain}'","content":"'${vps_ip}'","proxied":false}' \
            >/dev/null 2>&1

        echo ""

        box_top
        box_center "DOMAIN BERHASIL DIBUAT" "$green"
        box_middle
        box_left "Subdomain: $domain" "$green"
        box_bottom

        sleep 2
    fi
else
    domain="$1"
fi

vps_ip=$(curl -s ipinfo.io/ip)

if [[ ${pilih_domain:-} == "1" ]]; then
    domain_ip=$(getent ahosts "$domain" | awk '{print $1}' | head -n 1)

    if [ "$domain_ip" != "$vps_ip" ]; then
        echo ""

        box_top
        box_center "DOMAIN BELUM TERHUBUNG" "$red"
        box_middle
        box_left "Domain : $domain" "$yellow"
        box_left "IP VPS : $vps_ip" "$yellow"
        box_middle
        box_left "Pastikan record A domain mengarah ke IP VPS." "$red"
        box_bottom

        exit 1
    fi
fi

echo "$domain" >/etc/xray/domain

files=(
    /etc/xray/domain
    /var/log/xray/access.log
    /var/log/xray/error.log
    /etc/xray/vmess/.vmess.db
    /etc/xray/vless/.vless.db
    /etc/xray/trojan/.trojan.db
    /etc/xray/shadowsocks/.shadowsocks.db
    /etc/xray/ssh/.ssh.db
    /etc/ssh/.ssh.db
    /var/log/xray/access.log
    /var/log/xray/error.log
)

for file in "${files[@]}"; do
    [ ! -f "$file" ] && touch "$file"
    chmod 777 "$file"
done

chmod +x \
    /var/log/xray \
    /etc/xray \
    /etc/haproxy \
    /etc/xray/vmess \
    /etc/xray/vless \
    /etc/xray/trojan \
    /etc/xray/shadowsocks \
    /etc/xray/ssh

domain_ns="vpnnode.biz.id"
timezone="Asia/Jakarta"
slowdns_dir="/etc/slowdns"

ip=$(curl -sS ipv4.icanhazip.com)
city=$(curl -s ipinfo.io/city)
isp=$(curl -s ipinfo.io/org | cut -d " " -f 2-10)

domain=$(cat /etc/xray/domain)

cf_id="deltanevaangkasa@gmail.com"
cf_key="cfk_pbgN0TujS8Vcv0RtHkNLuzkqcT98FEKBfkxLdOpKc34c90c7"

key=$(
    curl -s "${BASE_URL}/access" |
        grep "### $vps_ip " |
        awk '{print $4}'
)

nginx_key_url="https://nginx.org/keys/nginx_signing.key"
gotop_url="https://raw.githubusercontent.com/xxxserxxx/gotop/master/scripts/download.sh"

ws_py_url="${BASE_URL}/Files/ws.py"
banner_url="${BASE_URL}/Files/issue.net"
dropbear_init_url="${BASE_URL}/Files/dropbear_init"
dropbear_conf_url="${BASE_URL}/Files/dropbear.conf"
dropbear_dss_url="${BASE_URL}/Files/dropbear_dss"
sshd_conf_url="${BASE_URL}/Files/sshd.conf"
common_password_url="${BASE_URL}/Files/common-password"
client_service_url="${BASE_URL}/Files/slowdns_client"
server_service_url="${BASE_URL}/Files/slowdns_server"
haproxy_cfg_url="${BASE_URL}/Files/haproxy.cfg"
xray_conf_url="${BASE_URL}/Files/xray.conf"
udp_url="${BASE_URL}/Files/udp-custom"
nginx_conf_url="${BASE_URL}/Files/nginx.conf"
badvpn_url="${BASE_URL}/Files/badvpn"
openvpn_url="${BASE_URL}/Files/openvpn.zip"
vmess_url="${BASE_URL}/Files/vmess.json"
vless_url="${BASE_URL}/Files/vless.json"
trojan_url="${BASE_URL}/Files/trojan.json"
shadowsocks_url="${BASE_URL}/Files/shadowsocks.json"
bbr_url="${BASE_URL}/Files/bbr.sh"
dnstt_client_url="${BASE_URL}/Files/dnstt-client"
dnstt_server_url="${BASE_URL}/Files/dnstt-server"

menu_dir="${BASE_URL}/Files/menu.zip"
bot_dir="${BASE_URL}/Files/bot.zip"

os_id=$(
    grep -w ID /etc/os-release |
        head -n1 |
        sed 's/ID=//g' |
        sed 's/"//g'
)

os_version=$(
    grep -w VERSION_ID /etc/os-release |
        head -n1 |
        sed 's/VERSION_ID=//g' |
        sed 's/"//g'
)

echo "Sistem Operasi: $os_id, Versi: $os_version"

if [ "$EUID" -ne 0 ]; then
    echo -e "${red}Script ini harus dijalankan sebagai root${neutral}"
    exit 1
fi

if ! apt update -y; then
    echo -e "${red}Gagal memperbarui daftar paket${neutral}"
fi

if ! dpkg -s sudo >/dev/null 2>&1; then
    if ! apt install sudo -y; then
        echo -e "${red}Gagal menginstal sudo${neutral}"
    fi
else
    echo -e "${green}sudo sudah terinstal, dilewati...${neutral}"
fi

if ! dpkg -s software-properties-common debconf-utils >/dev/null 2>&1; then
    if ! apt install -y --no-install-recommends software-properties-common debconf-utils; then
        echo -e "${red}Gagal menginstal paket dasar${neutral}"
    fi
else
    echo -e "${green}software-properties-common dan debconf-utils sudah terinstal, dilewati...${neutral}"
fi

if dpkg -s exim4 >/dev/null 2>&1; then
    if ! apt remove --purge -y exim4; then
        echo -e "${red}Gagal menghapus exim4${neutral}"
    else
        echo -e "${green}exim4 berhasil dihapus${neutral}"
    fi
else
    echo -e "${green}exim4 tidak terinstal, dilewati...${neutral}"
fi

if dpkg -s ufw >/dev/null 2>&1; then
    if ! apt remove --purge -y ufw; then
        echo -e "${red}Gagal menghapus ufw${neutral}"
    else
        echo -e "${green}ufw berhasil dihapus${neutral}"
    fi
else
    echo -e "${green}ufw tidak terinstal, dilewati...${neutral}"
fi

if dpkg -s firewalld >/dev/null 2>&1; then
    if ! apt remove --purge -y firewalld; then
        echo -e "${red}Gagal menghapus firewalld${neutral}"
    else
        echo -e "${green}firewalld berhasil dihapus${neutral}"
    fi
else
    echo -e "${green}firewalld tidak terinstal, dilewati...${neutral}"
fi

if ! echo iptables-persistent iptables-persistent/autosave_v4 boolean true |
    debconf-set-selections; then
    echo -e "${red}Gagal mengatur iptables-persistent IPv4${neutral}"
fi

if ! echo iptables-persistent iptables-persistent/autosave_v6 boolean true |
    debconf-set-selections; then
    echo -e "${red}Gagal mengatur iptables-persistent IPv6${neutral}"
fi

if ! debconf-set-selections <<<"keyboard-configuration keyboard-configuration/layout select English"; then
    echo -e "${red}Gagal mengatur tata letak keyboard${neutral}"
fi

if ! debconf-set-selections <<<"keyboard-configuration keyboard-configuration/variant select English"; then
    echo -e "${red}Gagal mengatur varian keyboard${neutral}"
fi

export DEBIAN_FRONTEND=noninteractive

if ! apt update -y; then
    echo -e "${red}Gagal memperbarui daftar paket${neutral}"
fi

if ! apt-get upgrade -y; then
    echo -e "${red}Gagal memperbarui sistem${neutral}"
else
    echo -e "${green}Pembaruan sistem berhasil${neutral}"
fi

if ! apt dist-upgrade -y; then
    echo -e "${red}Gagal melakukan pembaruan distribusi sistem${neutral}"
else
    echo -e "${green}Pembaruan distribusi sistem berhasil${neutral}"
fi

packages=(
    libnss3-dev
    liblzo2-dev
    libnspr4-dev
    pkg-config
    libpam0g-dev
    libcap-ng-dev
    libcap-ng-utils
    libselinux1-dev
    flex
    bison
    make
    libnss3-tools
    libevent-dev
    bc
    rsyslog
    dos2unix
    zlib1g-dev
    libssl-dev
    libsqlite3-dev
    sed
    dirmngr
    libxml-parser-perl
    build-essential
    gcc
    g++
    htop
    lsof
    tar
    wget
    curl
    ruby
    zip
    unzip
    p7zip-full
    libc6
    util-linux
    ca-certificates
    iptables
    iptables-persistent
    netfilter-persistent
    net-tools
    openssl
    gnupg
    gnupg2
    lsb-release
    shc
    cmake
    git
    whois
    screen
    socat
    xz-utils
    apt-transport-https
    gnupg1
    dnsutils
    cron
    bash-completion
    ntpdate
    chrony
    jq
    tmux
    python3
    python3-pip
    lsb-release
    gawk
    squid
    libncursesw5-dev
    libgdbm-dev
    tk-dev
    libffi-dev
    libbz2-dev
    checkinstall
    openvpn
    easy-rsa
    dropbear
)

for package in "${packages[@]}"; do
    if ! dpkg -s "$package" >/dev/null 2>&1; then
        if ! apt-get update -y; then
            echo -e "${red}Gagal memperbarui daftar paket${neutral}"
        fi

        if ! apt-get install -y "$package"; then
            echo -e "${red}Gagal menginstal $package${neutral}"
        fi
    else
        echo -e "${green}$package sudah terinstal, dilewati...${neutral}"
    fi
done

if [ -n "$city" ]; then
    if [ -f /etc/xray/city ]; then
        rm /etc/xray/city
    fi

    echo "$city" >>/etc/xray/city
else
    if [ -f /etc/xray/city ]; then
        rm /etc/xray/city
    fi

    echo "Informasi kota tidak tersedia" >>/etc/xray/city
fi

if [ -n "$isp" ]; then
    if [ -f /etc/xray/isp ]; then
        rm /etc/xray/isp
    fi

    echo "$isp" >>/etc/xray/isp
else
    if [ -f /etc/xray/isp ]; then
        rm /etc/xray/isp
    fi

    echo "Informasi ISP tidak tersedia" >>/etc/xray/isp
fi

if ! dpkg -s nodejs >/dev/null 2>&1; then
    curl -fsSL https://deb.nodesource.com/setup_20.x |
        sudo -E bash - ||
        echo -e "${red}Gagal mengunduh konfigurasi Node.js${neutral}"

    apt-get install -y nodejs ||
        echo -e "${red}Gagal menginstal Node.js${neutral}"
else
    echo -e "${green}Node.js sudah terinstal, dilewati...${neutral}"
fi

if ! dpkg -s vnstat >/dev/null 2>&1; then
    apt-get install -y vnstat ||
        echo -e "${red}Gagal menginstal vnstat${neutral}"

    wget -q https://humdi.net/vnstat/vnstat-2.9.tar.gz

    tar zxvf vnstat-2.9.tar.gz ||
        echo -e "${red}Gagal mengekstrak vnstat${neutral}"

    cd vnstat-2.9 ||
        echo -e "${red}Gagal masuk ke direktori vnstat-2.9${neutral}"

    ./configure --prefix=/usr --sysconfdir=/etc >/dev/null 2>&1 &&
        make >/dev/null 2>&1 &&
        make install >/dev/null 2>&1

    cd ||
        echo -e "${red}Gagal kembali ke direktori home${neutral}"

    net=$(
        ip -4 route ls |
            grep default |
            grep -Po '(?<=dev )(\S+)' |
            head -1
    )

    vnstat -i "$net"

    if grep -q 'Interface "eth0"' /etc/vnstat.conf; then
        sed -i 's/Interface "'""eth0""'"/Interface "'""$net""'"/g' /etc/vnstat.conf
    else
        echo -e "${yellow}Interface eth0 tidak ditemukan di /etc/vnstat.conf${neutral}"
    fi

    chown vnstat:vnstat /var/lib/vnstat -R ||
        echo -e "${red}Gagal mengubah kepemilikan direktori vnstat${neutral}"

    systemctl enable vnstat
    /etc/init.d/vnstat restart
else
    echo -e "${green}vnstat sudah terinstal, dilewati...${neutral}"
fi

rm -f /root/vnstat-2.9.tar.gz >/dev/null 2>&1 ||
    echo -e "${red}Gagal menghapus file vnstat-2.9.tar.gz${neutral}"

rm -rf /root/vnstat-2.9 >/dev/null 2>&1 ||
    echo -e "${red}Gagal menghapus direktori vnstat-2.9${neutral}"

ln -fs /usr/share/zoneinfo/$timezone /etc/localtime

os_id=$(
    grep -w ID /etc/os-release |
        head -n1 |
        sed 's/ID=//g' |
        sed 's/"//g'
)

if [[ $os_id == "ubuntu" ]]; then
    sudo apt update -y ||
        echo -e "${red}Gagal memperbarui daftar paket${neutral}"

    if ! dpkg -s software-properties-common >/dev/null 2>&1; then
        apt-get install --no-install-recommends software-properties-common ||
            echo -e "${red}Gagal menginstal software-properties-common${neutral}"
    else
        echo -e "${green}software-properties-common sudah terinstal, dilewati...${neutral}"
    fi

    rm -f /etc/apt/sources.list.d/nginx.list ||
        echo -e "${red}Gagal menghapus nginx.list${neutral}"

    if ! dpkg -s ubuntu-keyring >/dev/null 2>&1; then
        apt install -y ubuntu-keyring ||
            echo -e "${red}Gagal menginstal ubuntu-keyring${neutral}"
    else
        echo -e "${green}ubuntu-keyring sudah terinstal, dilewati...${neutral}"
    fi

    curl "$nginx_key_url" |
        gpg --dearmor |
        tee /usr/share/keyrings/nginx-archive-keyring.gpg >/dev/null

    echo "deb [signed-by=/usr/share/keyrings/nginx-archive-keyring.gpg] http://nginx.org/packages/ubuntu $(lsb_release -cs) nginx" |
        tee /etc/apt/sources.list.d/nginx.list

    echo -e "Package: *\nPin: origin nginx.org\nPin: release o=nginx\nPin-Priority: 900\n" |
        tee /etc/apt/preferences.d/99nginx

    if ! dpkg -s nginx >/dev/null 2>&1; then
        if ! apt install -y nginx; then
            echo -e "${red}Gagal menginstal nginx${neutral}"
        fi
    else
        echo -e "${green}nginx sudah terinstal, dilewati...${neutral}"
    fi

    if [ -f /etc/nginx/conf.d/default.conf ]; then
        rm /etc/nginx/conf.d/default.conf ||
            echo -e "${red}Gagal menghapus /etc/nginx/conf.d/default.conf${neutral}"
    else
        echo -e "${yellow}/etc/nginx/conf.d/default.conf tidak ditemukan, dilewati...${neutral}"
    fi

elif [[ $os_id == "debian" ]]; then
    sudo apt update -y ||
        echo -e "${red}Gagal memperbarui daftar paket${neutral}"

    rm -f /etc/apt/sources.list.d/nginx.list ||
        echo -e "${red}Gagal menghapus nginx.list${neutral}"

    if ! dpkg -s debian-archive-keyring >/dev/null 2>&1; then
        apt install -y debian-archive-keyring ||
            echo -e "${red}Gagal menginstal debian-archive-keyring${neutral}"
    else
        echo -e "${green}debian-archive-keyring sudah terinstal, dilewati...${neutral}"
    fi

    curl "$nginx_key_url" |
        gpg --dearmor |
        tee /usr/share/keyrings/nginx-archive-keyring.gpg >/dev/null

    echo "deb [signed-by=/usr/share/keyrings/nginx-archive-keyring.gpg] http://nginx.org/packages/debian $(lsb_release -cs) nginx" |
        tee /etc/apt/sources.list.d/nginx.list

    echo -e "Package: *\nPin: origin nginx.org\nPin: release o=nginx\nPin-Priority: 900\n" |
        tee /etc/apt/preferences.d/99nginx

    if ! dpkg -s nginx >/dev/null 2>&1; then
        apt install -y nginx ||
            echo -e "${red}Gagal menginstal nginx${neutral}"
    else
        echo -e "${green}nginx sudah terinstal, dilewati...${neutral}"
    fi
else
    echo -e "${red}Sistem operasi tidak didukung. Instalasi dihentikan.${neutral}"
    exit 1
fi

if [[ $os_id == "ubuntu" && $os_version == "18.04" ]]; then
    add-apt-repository -y ppa:vbernat/haproxy-2.6 ||
        echo -e "${red}Gagal menambahkan repositori HAProxy${neutral}"

    sudo apt update -y ||
        echo -e "${red}Gagal memperbarui daftar paket${neutral}"

    apt-get install -y haproxy=2.6.\* ||
        echo -e "${red}Gagal menginstal HAProxy${neutral}"

elif [[ $os_id == "ubuntu" && $os_version == "20.04" ]]; then
    add-apt-repository -y ppa:vbernat/haproxy-2.9 ||
        echo -e "${red}Gagal menambahkan repositori HAProxy${neutral}"

    sudo apt update -y ||
        echo -e "${red}Gagal memperbarui daftar paket${neutral}"

    apt-get install -y haproxy=2.9.\* ||
        echo -e "${red}Gagal menginstal HAProxy${neutral}"

elif [[ $os_id == "ubuntu" && $os_version == "22.04" ]]; then
    add-apt-repository -y ppa:vbernat/haproxy-3.0 ||
        echo -e "${red}Gagal menambahkan repositori HAProxy${neutral}"

    sudo apt update -y ||
        echo -e "${red}Gagal memperbarui daftar paket${neutral}"

    apt-get install -y haproxy=3.0.\* ||
        echo -e "${red}Gagal menginstal HAProxy${neutral}"

elif [[ $os_id == "ubuntu" && $os_version == "24.04" ]]; then
    add-apt-repository -y ppa:vbernat/haproxy-3.0 ||
        echo -e "${red}Gagal menambahkan repositori HAProxy${neutral}"

    sudo apt update -y ||
        echo -e "${red}Gagal memperbarui daftar paket${neutral}"

    apt-get install -y haproxy=3.0.\* ||
        echo -e "${red}Gagal menginstal HAProxy${neutral}"

elif [[ $os_id == "debian" && $os_version == "10" ]]; then
    curl https://haproxy.debian.net/bernat.debian.org.gpg |
        gpg --dearmor >/usr/share/keyrings/haproxy.debian.net.gpg ||
        echo -e "${red}Gagal menambahkan repositori HAProxy${neutral}"

    echo deb "[signed-by=/usr/share/keyrings/haproxy.debian.net.gpg]" \
        http://haproxy.debian.net \
        buster-backports-2.6 main \
        >/etc/apt/sources.list.d/haproxy.list ||
        echo -e "${red}Gagal menambahkan repositori HAProxy${neutral}"

    sudo apt update -y ||
        echo -e "${red}Gagal memperbarui daftar paket${neutral}"

    apt-get install -y haproxy=2.6.\* ||
        echo -e "${red}Gagal menginstal HAProxy${neutral}"

elif [[ $os_id == "debian" && $os_version == "11" ]]; then
    curl https://haproxy.debian.net/bernat.debian.org.gpg |
        gpg --dearmor >/usr/share/keyrings/haproxy.debian.net.gpg ||
        echo -e "${red}Gagal menambahkan repositori HAProxy${neutral}"

    echo deb "[signed-by=/usr/share/keyrings/haproxy.debian.net.gpg]" \
        http://haproxy.debian.net \
        bullseye-backports-3.0 main \
        >/etc/apt/sources.list.d/haproxy.list ||
        echo -e "${red}Gagal menambahkan repositori HAProxy${neutral}"

    sudo apt update -y ||
        echo -e "${red}Gagal memperbarui daftar paket${neutral}"

    apt-get install -y haproxy=3.0.\* ||
        echo -e "${red}Gagal menginstal HAProxy${neutral}"

elif [[ $os_id == "debian" && $os_version == "12" ]]; then
    curl https://haproxy.debian.net/bernat.debian.org.gpg |
        gpg --dearmor >/usr/share/keyrings/haproxy.debian.net.gpg ||
        echo -e "${red}Gagal menambahkan repositori HAProxy${neutral}"

    echo deb "[signed-by=/usr/share/keyrings/haproxy.debian.net.gpg]" \
        http://haproxy.debian.net \
        bookworm-backports-3.0 main \
        >/etc/apt/sources.list.d/haproxy.list ||
        echo -e "${red}Gagal menambahkan repositori HAProxy${neutral}"

    sudo apt update -y ||
        echo -e "${red}Gagal memperbarui daftar paket${neutral}"

    apt-get install -y haproxy=3.0.\* ||
        echo -e "${red}Gagal menginstal HAProxy${neutral}"
else
    echo -e "${red}Sistem operasi tidak didukung. Instalasi dihentikan.${neutral}"
    exit 1
fi

if [ -n "$menu_dir" ]; then
    wget "$menu_dir" -O /tmp/menu.zip >/dev/null 2>&1 ||
        echo -e "${red}Gagal mengunduh menu.zip${neutral}"

    cd /tmp || exit

    7z x -p@RSCoders45rs menu.zip >/dev/null 2>&1 ||
        echo -e "${red}Gagal mengekstrak menu.zip${neutral}"

    chmod +x menu/* >/dev/null 2>&1 ||
        echo -e "${red}Gagal memberikan izin eksekusi pada file menu${neutral}"

    mv menu/* /usr/bin/ >/dev/null 2>&1 ||
        echo -e "${red}Gagal menyalin file menu ke /usr/bin${neutral}"

    rm -rf menu
    rm -rf menu.zip

    cd || exit
else
    echo -e "${yellow}menu_dir belum diatur, unduhan menu.zip dilewati...${neutral}"
fi

if [ -n "$dropbear_conf_url" ]; then
    [ -f /etc/default/dropbear ] &&
        rm /etc/default/dropbear

    wget -q -O /etc/default/dropbear "$dropbear_conf_url" >/dev/null 2>&1 ||
        echo -e "${red}Gagal mengunduh dropbear.conf${neutral}"

    [ -f /etc/init.d/dropbear ] &&
        rm /etc/init.d/dropbear

    wget -q -O /etc/init.d/dropbear "$dropbear_init_url" &&
        chmod +x /etc/init.d/dropbear >/dev/null 2>&1 ||
        echo -e "${red}Gagal mengunduh dropbear_init${neutral}"

    [ -f /etc/dropbear/dropbear_dss_host_key ] &&
        rm /etc/dropbear/dropbear_dss_host_key

    wget -q \
        -O /etc/dropbear/dropbear_dss_host_key \
        "$dropbear_dss_url" &&
        chmod +x /etc/dropbear/dropbear_dss_host_key >/dev/null 2>&1 ||
        echo -e "${red}Gagal mengunduh dropbear_dss_host_key${neutral}"
else
    echo -e "${yellow}dropbear_conf_url belum diatur, unduhan konfigurasi Dropbear dilewati...${neutral}"
fi

if [ -n "$sshd_conf_url" ]; then
    [ -f /etc/ssh/sshd_config ] &&
        rm /etc/ssh/sshd_config

    wget -q -O /etc/ssh/sshd_config "$sshd_conf_url" >/dev/null 2>&1 ||
        echo -e "${red}Gagal mengunduh konfigurasi SSH${neutral}"
else
    echo -e "${yellow}sshd_conf_url belum diatur, unduhan konfigurasi SSH dilewati...${neutral}"
fi

if [ -n "$banner_url" ]; then
    wget -q -O /etc/issue.net "$banner_url" &&
        chmod +x /etc/issue.net >/dev/null 2>&1 ||
        echo -e "${red}Gagal mengunduh banner issue.net${neutral}"
else
    echo -e "${yellow}banner_url belum diatur, unduhan banner dilewati...${neutral}"
fi

if [ -n "$common_password_url" ]; then
    [ -f /etc/pam.d/common-password ] &&
        rm /etc/pam.d/common-password

    wget -O /etc/pam.d/common-password "$common_password_url" >/dev/null 2>&1 ||
        echo -e "${red}Gagal mengunduh common-password${neutral}"
else
    echo -e "${yellow}common_password_url belum diatur, unduhan common-password dilewati...${neutral}"
fi

if [ -n "$ws_py_url" ]; then
    wget -O /usr/bin/ws.py "$ws_py_url" >/dev/null 2>&1 &&
        chmod +x /usr/bin/ws.py ||
        echo -e "${red}Gagal mengunduh ws.py${neutral}"
else
    echo -e "${yellow}ws_py_url belum diatur, unduhan ws.py dilewati...${neutral}"
fi

if [ ! -d "$slowdns_dir" ]; then
    mkdir -p "$slowdns_dir" ||
        echo -e "${red}Gagal membuat direktori $slowdns_dir${neutral}"
fi

if [ -n "$dnstt_server_url" ]; then
    wget \
        -O /etc/slowdns/dnstt-server \
        "$dnstt_server_url" \
        >/dev/null 2>&1 &&
        chmod +x /etc/slowdns/dnstt-server ||
        echo -e "${red}Gagal mengunduh atau memberikan izin eksekusi pada DNSTT Server${neutral}"
else
    echo -e "${yellow}dnstt_server_url belum diatur, unduhan DNSTT Server dilewati...${neutral}"
fi

if [ -n "$dnstt_client_url" ]; then
    wget \
        -O /etc/slowdns/dnstt-client \
        "$dnstt_client_url" \
        >/dev/null 2>&1 &&
        chmod +x /etc/slowdns/dnstt-client ||
        echo -e "${red}Gagal mengunduh atau memberikan izin eksekusi pada DNSTT Client${neutral}"
else
    echo -e "${yellow}dnstt_client_url belum diatur, unduhan DNSTT Client dilewati...${neutral}"
fi

if [ -f /etc/slowdns/dnstt-server ]; then
    /etc/slowdns/dnstt-server \
        -gen-key \
        -privkey-file /etc/slowdns/server.key \
        -pubkey-file /etc/slowdns/server.pub ||
        echo -e "${red}Gagal membuat kunci DNSTT Server${neutral}"
else
    echo -e "${red}DNSTT Server tidak ditemukan, pembuatan kunci dilewati...${neutral}"
fi

if [ -f /etc/pam.d/common-password ]; then
    chmod +x /etc/pam.d/common-password ||
        echo -e "${red}Gagal memberikan izin pada common-password${neutral}"
else
    echo -e "${yellow}/etc/pam.d/common-password tidak ditemukan, perubahan izin dilewati...${neutral}"
fi

if curl -s "$gotop_url" | bash; then
    chmod +x gotop &&
        sudo mv gotop /usr/local/bin/ ||
        echo -e "${red}Gagal memberikan izin atau memindahkan gotop${neutral}"
else
    echo -e "${red}Gagal mengunduh atau menjalankan script gotop${neutral}"
fi

if [ -f /etc/haproxy/haproxy.cfg ]; then
    rm /etc/haproxy/haproxy.cfg

    echo -e "${yellow}Konfigurasi haproxy.cfg lama berhasil dihapus${neutral}"
fi

if dpkg -s apache2 >/dev/null 2>&1; then
    apt-get remove --purge apache2 -y

    echo -e "${yellow}Apache berhasil dihapus${neutral}"
else
    echo -e "${green}Apache tidak terinstal, dilewati...${neutral}"
fi

if wget \
    -O /etc/haproxy/haproxy.cfg \
    "$haproxy_cfg_url" \
    >/dev/null 2>&1; then
    echo -e "${green}Berhasil mengunduh haproxy.cfg${neutral}"
else
    echo -e "${red}Gagal mengunduh haproxy.cfg${neutral}"
fi

if wget \
    -O /etc/nginx/conf.d/xray.conf \
    "$xray_conf_url" \
    >/dev/null 2>&1; then
    echo -e "${green}Berhasil mengunduh xray.conf${neutral}"
else
    echo -e "${red}Gagal mengunduh xray.conf${neutral}"
fi

if wget \
    -O /etc/xray/vmess/config.json \
    "$vmess_url" \
    >/dev/null 2>&1; then
    echo -e "${green}Berhasil mengunduh konfigurasi VMess${neutral}"
else
    echo -e "${red}Gagal mengunduh konfigurasi VMess${neutral}"
fi

if wget \
    -O /etc/xray/vless/config.json \
    "$vless_url" \
    >/dev/null 2>&1; then
    echo -e "${green}Berhasil mengunduh konfigurasi VLESS${neutral}"
else
    echo -e "${red}Gagal mengunduh konfigurasi VLESS${neutral}"
fi

if wget \
    -O /etc/xray/trojan/config.json \
    "$trojan_url" \
    >/dev/null 2>&1; then
    echo -e "${green}Berhasil mengunduh konfigurasi Trojan${neutral}"
else
    echo -e "${red}Gagal mengunduh konfigurasi Trojan${neutral}"
fi

if wget \
    -O /etc/xray/shadowsocks/config.json \
    "$shadowsocks_url" \
    >/dev/null 2>&1; then
    echo -e "${green}Berhasil mengunduh konfigurasi Shadowsocks${neutral}"
else
    echo -e "${red}Gagal mengunduh konfigurasi Shadowsocks${neutral}"
fi

if wget \
    -O /usr/bin/udp \
    "$udp_url" \
    >/dev/null 2>&1 &&
    chmod +x /usr/bin/udp >/dev/null 2>&1; then
    echo -e "${green}Berhasil mengunduh UDP Custom${neutral}"
else
    echo -e "${red}Gagal mengunduh UDP Custom${neutral}"
fi

if wget \
    -O /etc/nginx/nginx.conf \
    "$nginx_conf_url" \
    >/dev/null 2>&1 &&
    chmod +x /etc/nginx/nginx.conf >/dev/null 2>&1; then
    echo -e "${green}Berhasil mengunduh konfigurasi nginx.conf${neutral}"
else
    echo -e "${red}Gagal mengunduh konfigurasi nginx.conf${neutral}"
fi

if wget \
    -O /usr/bin/badvpn \
    "$badvpn_url" \
    >/dev/null 2>&1 &&
    chmod +x /usr/bin/badvpn >/dev/null 2>&1; then
    echo -e "${green}Berhasil mengunduh BadVPN${neutral}"
else
    echo -e "${red}Gagal mengunduh BadVPN${neutral}"
fi

if [[ "$(sysctl net.ipv4.tcp_congestion_control | awk '{print $3}')" != "bbr" ]]; then
    bash -c "$(curl -L "$bbr_url")"
else
    echo -e "${green}BBR sudah aktif, instalasi dilewati...${neutral}"
fi

interface=$(
    ip -4 route ls |
        grep default |
        grep -Po '(?<=dev )(\S+)' |
        head -1
)

if iptables \
    -t nat \
    -A PREROUTING \
    -i "$interface" \
    -p udp \
    -m udp \
    --dport 53 \
    -j REDIRECT \
    --to-ports 5300; then

    iptables-save >/etc/iptables/rules.v4
else
    echo -e "${red}Gagal menambahkan aturan PREROUTING iptables${neutral}"
fi

if iptables \
    -t nat \
    -A POSTROUTING \
    -s 10.8.0.0/24 \
    -o "$interface" \
    -j MASQUERADE; then

    iptables-save >/etc/iptables/rules.v4
else
    echo -e "${red}Gagal menambahkan aturan POSTROUTING iptables untuk 10.8.0.0/24${neutral}"
fi

if iptables \
    -t nat \
    -A POSTROUTING \
    -s 20.8.0.0/24 \
    -o "$interface" \
    -j MASQUERADE; then

    iptables-save >/etc/iptables/rules.v4
else
    echo -e "${red}Gagal menambahkan aturan POSTROUTING iptables untuk 20.8.0.0/24${neutral}"
fi

if ! grep -q "^net.ipv4.ip_forward=1" /etc/sysctl.conf; then
    sed -i \
        's/#net.ipv4.ip_forward=1/net.ipv4.ip_forward=1/' \
        /etc/sysctl.conf

    if ! grep -q "^net.ipv4.ip_forward=1" /etc/sysctl.conf; then
        echo "net.ipv4.ip_forward=1" >>/etc/sysctl.conf
    fi
else
    echo -e "${green}net.ipv4.ip_forward=1 sudah tersedia di /etc/sysctl.conf, dilewati...${neutral}"
fi

sysctl -p

if iptables-save >/etc/iptables/rules.v4; then
    echo -e "${green}Aturan iptables berhasil disimpan${neutral}"
else
    echo -e "${red}Gagal menyimpan aturan iptables${neutral}"
fi

if ! command -v xray >/dev/null 2>&1; then
    bash -c "$(curl -L https://github.com/XTLS/Xray-install/raw/main/install-release.sh)" \
        @ install \
        -u www-data \
        --version 24.9.30
else
    echo -e "${green}Xray sudah terinstal, instalasi dilewati...${neutral}"
fi

if [ ! -d "/root/.acme.sh" ]; then
    mkdir /root/.acme.sh
fi

systemctl daemon-reload
systemctl stop haproxy
systemctl stop nginx

if [ ! -f "/root/.acme.sh/acme.sh" ]; then
    curl https://get.acme.sh | sh

    chmod +x /root/.acme.sh/acme.sh
fi

domain=$(cat /etc/xray/domain)

/root/.acme.sh/acme.sh --upgrade --auto-upgrade

/root/.acme.sh/acme.sh \
    --set-default-ca \
    --server letsencrypt

/root/.acme.sh/acme.sh \
    --issue \
    -d "$domain" \
    --standalone \
    -k ec-256

/root/.acme.sh/acme.sh \
    --installcert \
    -d "$domain" \
    --fullchainpath /etc/xray/xray.crt \
    --keypath /etc/xray/xray.key \
    --ecc

cat \
    /etc/xray/xray.crt \
    /etc/xray/xray.key |
    tee /etc/haproxy/rs.pem

chown www-data:www-data /etc/xray/xray.key
chown www-data:www-data /etc/xray/xray.crt

sub=$(tr </dev/urandom -dc a-z0-9 | head -c7)

sub_domain="$sub.$domain_ns"
ns_domain="$sub_domain"

set -euo pipefail

zone=$(
    curl -sLX GET \
        "https://api.cloudflare.com/client/v4/zones?name=${domain_ns}&status=active" \
        -H "X-Auth-Email: ${cf_id}" \
        -H "X-Auth-Key: ${cf_key}" \
        -H "Content-Type: application/json" |
        jq -r .result[0].id
)

record=$(
    curl -sLX GET \
        "https://api.cloudflare.com/client/v4/zones/${zone}/dns_records?name=${ns_domain}" \
        -H "X-Auth-Email: ${cf_id}" \
        -H "X-Auth-Key: ${cf_key}" \
        -H "Content-Type: application/json" |
        jq -r .result[0].id
)

if [[ "${#record}" -le 10 ]]; then
    record=$(
        curl -sLX POST \
            "https://api.cloudflare.com/client/v4/zones/${zone}/dns_records" \
            -H "X-Auth-Email: ${cf_id}" \
            -H "X-Auth-Key: ${cf_key}" \
            -H "Content-Type: application/json" \
            --data '{"type":"NS","name":"'${ns_domain}'","content":"'${domain}'","proxied":false}' |
            jq -r .result.id
    )
fi

result=$(
    curl -sLX PUT \
        "https://api.cloudflare.com/client/v4/zones/${zone}/dns_records/${record}" \
        -H "X-Auth-Email: ${cf_id}" \
        -H "X-Auth-Key: ${cf_key}" \
        -H "Content-Type: application/json" \
        --data '{"type":"NS","name":"'${ns_domain}'","content":"'${domain}'","proxied":false}'
)

echo "$ns_domain" >/etc/xray/dns

mkdir -p /usr/lib/openvpn/ ||
    echo -e "${red}Gagal membuat direktori /usr/lib/openvpn/${neutral}"

if [ -d "/etc/openvpn/" ]; then
    echo -e "${green}Direktori /etc/openvpn/ sudah tersedia, proses dilanjutkan...${neutral}"
else
    mkdir -p /usr/lib/openvpn/ ||
        echo -e "${red}Gagal membuat direktori /usr/lib/openvpn/${neutral}"
fi

if wget \
    -O /etc/openvpn/openvpn.zip \
    "$openvpn_url" \
    >/dev/null 2>&1; then

    if unzip \
        -d /etc/openvpn/ \
        /etc/openvpn/openvpn.zip \
        >/dev/null 2>&1; then

        echo -e "${green}OpenVPN berhasil diunduh dan diekstrak${neutral}"

        rm -f /etc/openvpn/openvpn.zip
    else
        echo -e "${red}Gagal mengekstrak openvpn.zip${neutral}"
    fi
else
    echo -e "${red}Gagal mengunduh openvpn.zip${neutral}"
fi

cat >/etc/openvpn/client-tcp.ovpn <<EOF
auth-user-pass
client
dev tun
proto tcp
remote $ip 1194
persist-key
persist-tun
pull
resolv-retry infinite
nobind
user nobody
comp-lzo
remote-cert-tls server
verb 3
mute 2
connect-retry 5 5
connect-retry-max 8080
mute-replay-warnings
redirect-gateway def1
script-security 2
cipher none
auth none
EOF

cat >/etc/openvpn/client-udp.ovpn <<EOF
auth-user-pass
client
dev tun
proto udp
remote $ip 2200
persist-key
persist-tun
pull
resolv-retry infinite
nobind
user nobody
comp-lzo
remote-cert-tls server
verb 3
mute 2
connect-retry 5 5
connect-retry-max 8080
mute-replay-warnings
redirect-gateway def1
script-security 2
cipher none
auth none
EOF

cat >/etc/openvpn/client-ssl.ovpn <<EOF
auth-user-pass
client
dev tun
proto tcp
remote $ip 443
persist-key
persist-tun
pull
resolv-retry infinite
nobind
user nobody
comp-lzo
remote-cert-tls server
verb 3
mute 2
connect-retry 5 5
connect-retry-max 8080
mute-replay-warnings
redirect-gateway def1
script-security 2
cipher none
auth none
EOF

input_cert_ovpn() {
    for config in client-tcp client-udp client-ssl; do
        echo '<ca>' >>"/etc/openvpn/${config}.ovpn"

        cat /etc/openvpn/ca.crt >>"/etc/openvpn/${config}.ovpn"

        echo '</ca>' >>"/etc/openvpn/${config}.ovpn"

        cp \
            "/etc/openvpn/${config}.ovpn" \
            "/var/www/html/${config}.ovpn"
    done

    cd /var/www/html/ || exit

    zip \
        allovpn.zip \
        client-tcp.ovpn \
        client-udp.ovpn \
        client-ssl.ovpn \
        >/dev/null 2>&1

    sed -i \
        's/#AUTOSTART="all"/AUTOSTART="all"/g' \
        /etc/default/openvpn

    cd || exit
}

input_cert_ovpn

if ! zip \
    -j /var/www/html/allovpn.zip \
    /var/www/html/*.ovpn; then

    echo -e "${red}Gagal membuat file ZIP untuk seluruh konfigurasi client OpenVPN.${neutral}"
fi

if ! sed -i \
    's/#AUTOSTART="all"/AUTOSTART="all"/g' \
    /etc/default/openvpn; then

    echo -e "${red}Gagal mengaktifkan autostart OpenVPN.${neutral}"
fi

cat >/usr/bin/config.json <<EOF
{
  "listen": ":2100",
  "stream_buffer": 33554432,
  "receive_buffer": 83886080,
  "auth": {
    "mode": "passwords"
  }
}
EOF

cat >/etc/cron.d/xp_all <<EOF
SHELL=/bin/sh
PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
2 0 * * * root /usr/bin/exp
EOF

cat >/root/.profile <<EOF
# ~/.profile: executed by Bourne-compatible login shells.
if [ "\$BASH" ]; then
  if [ -f ~/.bashrc ]; then
    . ~/.bashrc
  fi
fi
mesg n || true
rs dashboard
EOF

chmod 644 /root/.profile

cat >/root/.bashrc <<EOF
# ~/.bashrc: executed by bash(1) for non-login shells.
cat /dev/null > ~/.bash_history && history -c
EOF

chmod 644 /root/.bashrc

cat >/etc/shells <<EOF
# /etc/shells: valid login shells
/bin/sh
/bin/bash
/usr/bin/bash
/bin/rbash
/usr/bin/rbash
/bin/dash
/usr/bin/dash
/usr/bin/screen
/usr/bin/tmux
/bin/false
/usr/sbin/nologin
EOF

chmod +x /etc/shells

cat /dev/null >~/.bash_history &&
    history -c

cat >/etc/cron.d/daily_reboot <<EOF
SHELL=/bin/sh
PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
0 5 * * * root /sbin/reboot
EOF

cat >/etc/cron.d/logclear <<EOF
SHELL=/bin/sh
PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
0 */6 * * * root /usr/bin/logclear
EOF

service cron restart

cat >/home/daily_reboot <<EOF
5
EOF

capabilities="CAP_NET_ADMIN CAP_NET_BIND_SERVICE"

limits="LimitNPROC=10000
LimitNOFILE=1000000"

restart="Restart=on-failure
RestartPreventExitStatus=23"

wanted_by="WantedBy=multi-user.target"

after="After=network.target nss-lookup.target"

create_service() {
    local name=$1
    local description=$2
    local exec_start=$3

    cat >/etc/systemd/system/${name}@config.service <<EOF
[Unit]
Description=${description} %i
${after}

[Service]
User=www-data
CapabilityBoundingSet=${capabilities}
AmbientCapabilities=${capabilities}
NoNewPrivileges=yes
ExecStart=${exec_start}
${restart}
${limits}

[Install]
${wanted_by}
EOF
}

create_service \
    "vmess" \
    "Server Xray VMess INTERFLAZZ.MY.ID" \
    "/usr/local/bin/xray run -config /etc/xray/vmess/%i.json"

create_service \
    "vless" \
    "Server Xray VLESS INTERFLAZZ.MY.ID" \
    "/usr/local/bin/xray run -config /etc/xray/vless/%i.json"

create_service \
    "trojan" \
    "Server Xray Trojan INTERFLAZZ.MY.ID" \
    "/usr/local/bin/xray run -config /etc/xray/trojan/%i.json"

create_service \
    "shadowsocks" \
    "Server Shadowsocks INTERFLAZZ.MY.ID" \
    "/usr/local/bin/xray run -config /etc/xray/shadowsocks/%i.json"

mkdir -p /etc/systemd/system/xray@.service.d

cat >/etc/systemd/system/xray@.service.d/10-donot_touch_single_conf.conf <<EOF
[Service]
ExecStart=
ExecStart=/usr/local/bin/xray run -config /etc/xray/%i.json
EOF

sudo systemctl daemon-reload

sudo systemctl stop xray
sudo systemctl disable xray

sudo systemctl disable dropbear
sudo systemctl stop dropbear

rm -rf /lib/systemd/system/dropbear.service

sudo systemctl daemon-reload

/etc/init.d/dropbear start
/etc/init.d/dropbear restart

cat >/etc/systemd/system/ws.service <<EOF
[Unit]
Description=Proxy WebSocket Python
${after}

[Service]
Type=simple
User=root
CapabilityBoundingSet=${capabilities}
AmbientCapabilities=${capabilities}
NoNewPrivileges=true
ExecStart=/usr/bin/python3 -O /usr/bin/ws.py
${restart}

[Install]
${wanted_by}
EOF

cat >/etc/systemd/system/udp.service <<EOF
[Unit]
Description=Server VPN UDP Custom
After=network.target

[Service]
User=root
WorkingDirectory=/usr/bin
ExecStart=/usr/bin/udp server -exclude 2200,7300,7200,7100,323,10008,10004 /usr/bin/config.json
Environment=HYSTERIA_LOG_LEVEL=info
CapabilityBoundingSet=CAP_NET_ADMIN CAP_NET_BIND_SERVICE CAP_NET_RAW
AmbientCapabilities=CAP_NET_ADMIN CAP_NET_BIND_SERVICE CAP_NET_RAW
NoNewPrivileges=true
${limits}
${restart}

[Install]
${wanted_by}
EOF

cat >/etc/systemd/system/limitip.service <<EOF
[Unit]
Description=Layanan Pembatasan Penggunaan IP Xray
After=syslog.target network-online.target

[Service]
User=root
NoNewPrivileges=true
ExecStart=/bin/bash -c '/usr/bin/limitipssh 15 & /usr/bin/limitip 15 & wait'
Restart=on-failure

[Install]
WantedBy=multi-user.target
EOF

cat >/etc/systemd/system/limitquota.service <<EOF
[Unit]
Description=Layanan Pembatasan Kuota Xray
After=syslog.target network-online.target

[Service]
User=root
NoNewPrivileges=true
ExecStart=/usr/bin/quota
Restart=on-failure

[Install]
WantedBy=multi-user.target
EOF

cat >/etc/systemd/system/badvpn.service <<EOF
[Unit]
Description=Layanan UDP BadVPN
After=syslog.target network-online.target

[Service]
User=root
NoNewPrivileges=true
ExecStart=/usr/bin/badvpn --listen-addr 127.0.0.1:7100 --listen-addr 127.0.0.1:7200 --listen-addr 127.0.0.1:7300 --max-clients 500
Restart=on-failure
RestartPreventExitStatus=23
LimitNPROC=10000
LimitNOFILE=1000000

[Install]
WantedBy=multi-user.target
EOF

cat >/etc/systemd/system/dnstt-server.service <<EOF
[Unit]
Description=Server SlowDNS
After=network.target nss-lookup.target

[Service]
Type=simple
User=root
CapabilityBoundingSet=CAP_NET_ADMIN CAP_NET_BIND_SERVICE
AmbientCapabilities=CAP_NET_ADMIN CAP_NET_BIND_SERVICE
NoNewPrivileges=true
ExecStart=/etc/slowdns/dnstt-server -udp 0.0.0.0:5300 -privkey-file /etc/slowdns/server.key xxxx 127.0.0.1:443
Restart=on-failure

[Install]
WantedBy=multi-user.target
EOF

cat >/etc/systemd/system/dnstt-client.service <<EOF
[Unit]
Description=Client SlowDNS
After=network.target nss-lookup.target

[Service]
Type=simple
User=root
CapabilityBoundingSet=CAP_NET_ADMIN CAP_NET_BIND_SERVICE
AmbientCapabilities=CAP_NET_ADMIN CAP_NET_BIND_SERVICE
NoNewPrivileges=true
ExecStart=/etc/slowdns/dnstt-client -doh https://cloudflare-dns.com/dns-query --pubkey-file /etc/slowdns/server.pub xxxx 127.0.0.1:88
Restart=on-failure

[Install]
WantedBy=multi-user.target
EOF

sed -i \
    "s/xxxx/$ns_domain/g" \
    /etc/systemd/system/dnstt-client.service

sed -i \
    "s/xxxx/$ns_domain/g" \
    /etc/systemd/system/dnstt-server.service

if [ -f /root/.key ]; then
    rm -f /root/.key
fi

echo "$key" >>/root/.key

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

for config in vmess vless trojan shadowsocks; do
    sudo sed -i \
        "s/1d1c1d94-6987-4658-a4dc-8821a30fe7e0/$uuid_baru/g" \
        "/etc/xray/$config/config.json"
done

npm i \
    --prefix /usr/bin \
    express \
    express-fileupload

setup_bot() {
    if [ ! -d "/root/.bot" ]; then
        mkdir -p /root/.bot
    fi

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

        npm install \
            --prefix /root/.bot \
            express \
            telegraf \
            axios \
            moment \
            sqlite3
    fi

    if [ ! -f /root/.bot/app.js ]; then
        wget \
            -q \
            -O /tmp/bot.zip \
            "$bot_dir"

        cd /tmp || exit

        7z x \
            -p@RSCoders45rs \
            bot.zip \
            >/dev/null 2>&1

        chmod +x bot/* >/dev/null 2>&1

        mv bot/* /root/.bot/ >/dev/null 2>&1

        rm -rf bot
        rm -rf bot.zip

        cd || exit
    fi

    if [ -n "$(ls -A /root/.bot)" ]; then
        chmod +x /root/.bot/*
    fi
}

setup_bot

swap_file="/swapfile"
swap_size="3G"

if [ ! -f "$swap_file" ]; then
    fallocate -l "$swap_size" "$swap_file"

    chmod 600 "$swap_file"

    mkswap "$swap_file"

    swapon "$swap_file"

    echo "$swap_file swap swap defaults 0 0" >>/etc/fstab

    echo -e "${green}Swap RAM berhasil ditambahkan dengan ukuran $swap_size${neutral}"
else
    echo -e "${yellow}Swap sudah tersedia, penambahan Swap RAM dilewati...${neutral}"
fi

sudo systemctl daemon-reload

services=(
    "vmess@config.service"
    "vless@config.service"
    "trojan@config.service"
    "shadowsocks@config.service"
    "haproxy.service"
    "ws.service"
    "udp.service"
    "limitip.service"
    "limitquota.service"
    "badvpn.service"
    "nginx.service"
    "dnstt-server.service"
    "dnstt-client.service"
    "ssh.service"
    "dropbear.service"
)

for service in "${services[@]}"; do
    sudo systemctl enable "$service"
    sudo systemctl start "$service"
    sudo systemctl restart "$service"

    echo -ne "Memulai ulang $service...\r"

    sleep 1

    echo -ne "Memulai ulang $service...${green} Berhasil! ${neutral}\n"
done

sudo systemctl restart netfilter-persistent

clear

box_top
box_center "INTERFLAZZ.MY.ID" "$green"
box_center "AUTOSCRIPT PREMIUM" "$bold_white"
box_middle
box_center "INSTALASI SELESAI" "$green"
box_middle
box_center "Selamat! Proses instalasi telah selesai." "$green"
box_center "Server siap digunakan setelah reboot." "$yellow"
box_middle
box_left "WhatsApp ~ https://wa.me/6285956131443" "$green"
box_left "Telegram ~ https://t.me/interflazz" "$blue"
box_bottom

echo ""
read -p "Tekan ENTER untuk reboot server..."

reboot