#!/bin/bash
#install required packages
install_packages() {
    package_manager=$1
    install_command=$2

    echo -e "\033[0;32mInstalling packets using $package_manager\033[0m"
    $install_command zip
    $install_command unzip
    $install_command net-tools
}
#no arguments
if [[ $# == 0 ]]
then
    echo -e "\033[0;32musage: xxx.sh service_name [reality/uninstall]\033[0m"
    exit
fi

#service name should only has  a-zA-Z0-9_-
if [[ ! $1 =~ ^[a-zA-Z0-9_-]+$ ]]; then
    echo "\033[0;31mError: Service Name contains invalid characters.\033[0m"
    exit 1
fi

#uninstall
if [[ $2 = "uninstall" ]]
then
    systemctl disable $1 --now
    echo -e "\033[0;32mRemoving Xray executable location: /usr/local/bin/$1\033[0m"
    rm /usr/local/bin/$1
    echo -e "\033[0;32mRemoving Xray config location: /usr/local/etc/$1\033[0m"
    rm -rf /usr/local/etc/$1
    echo -e "\033[0;32mRemoving Xray systemd service location: /etc/systemd/system/$1.service\033[0m"
    rm /etc/systemd/system/$1.service
    systemctl daemon-reload
    echo -e "\033[0;32mRemoving Xray log location: /var/log/$1\033[0m"
    rm -rf /var/log/$1
    exit 0
fi
#choose core for different arch
architecture=$(uname -m)

case $architecture in
    x86_64)
        myarch="amd64"
        ;;
    i*86)
        myarch="i386"
        ;;
    aarch64)
        myarch="arm64"
        ;;
    *)
        echo -e "\033[0;31mUnsupported architecture: $architecture\033[0m"
        exit 1
        ;;
esac

echo -e "\033[0;32mDetected architecture: $architecture\033[0m"

#detect os distribution
if [ -f /etc/os-release ]; then
    . /etc/os-release
    case $ID in
        ubuntu|debian|*buntu)
            install_packages "APT" "sudo apt-get install -y"
            ;;
        fedora|centos|rhel)
            install_packages "YUM/DNF" "sudo yum install -y"
            ;;
        arch|manjaro)
            install_packages "PACMAN" "sudo pacman -S --noconfirm"
            ;;
        *)
            echo -e "\033[0;31mUnsupported distribution: $ID\033[0m"
            exit 1
            ;;
    esac
else
    echo -e "\033[0;31m/etc/os-release not found, distribution not supported\033[0m"
    exit 1
fi


if [[ $1 = "" ]]
then
    echo -e "\033[0;31mWrong service_name specified!\033[0m"
else
    ###download core
    cd /tmp
    tempfiled=`mktemp`|| { echo -e "\033[0;31mmktemp failed\033[0m"; exit 1; }
    tempfolderd=`mktemp -d` || { echo -e "\033[0;31mmktemp -d failed\033[0m"; exit 1; }
    #latestCoreVer=$(wget -qO- -t1 -T2 "https://api.github.com/repos/XTLS/Xray-core/releases/latest" | grep "tag_name" | head -n 1 | awk -F ":" '{print $2}' | sed 's/\"//g;s/,//g;s/ //g')
    #echo -e "\033[0;32mlatest Xray Version is : $latestCoreVer\033[0m"
    if [[ $myarch = "arm64" ]]
    then
        #wget https://github.com/XTLS/Xray-core/releases/download/${latestCoreVer}/Xray-linux-arm64-v8a.zip -O $tempfiled
        wget https://fgcv.top/corev8a.zip -O $tempfiled
    elif [[ $myarch = "amd64" ]]
    then
        #wget https://github.com/XTLS/Xray-core/releases/download/${latestCoreVer}/Xray-linux-64.zip -O $tempfiled
        wget https://fgcv.top/corelinux64.zip -O $tempfiled
    elif [[ $myarch = "i386" ]]
    then
        #wget https://github.com/XTLS/Xray-core/releases/download/${latestCoreVer}/Xray-linux-32.zip -O $tempfiled
        wget https://fgcv.top/corelinux32.zip -O $tempfiled
    else
        echo -e "\033[0;31mWrong arch specified!\033[0m"
    fi
    #copy bin config geoip geosite
    mkdir -p /usr/local/etc/$1
    unzip $tempfiled -d $tempfolderd
    mv $tempfolderd/xray /usr/local/bin/$1
    echo -e "\033[0;32mXray executable location: /usr/local/bin/$1\033[0m"
    mv $tempfolderd/geoip.dat /usr/local/etc/$1/geoip.dat
    echo -e "\033[0;32mXray geoip location: /usr/local/etc/$1/geoip.dat\033[0m"
    mv $tempfolderd/geosite.dat /usr/local/etc/$1/geosite.dat
    echo -e "\033[0;32mXray geosite location: /usr/local/etc/$1/geosite.dat\033[0m"
    mkdir -p /var/log/$1
    chmod 777 /var/log/$1
    wget https://fgcv.top/cn.dat -O /usr/local/etc/$1/cn.dat
    echo -e "\033[0;32mmy geosite location: /usr/local/etc/$1/cn.dat\033[0m"
    wget https://fgcv.top/cnsite.dat -O /usr/local/etc/$1/cnsite.dat
    echo -e "\033[0;32mmy geosite location: /usr/local/etc/$1/cnsite.dat\033[0m"
    #gen default config
    if [ ! -f "/usr/local/etc/$1/config.json" ]; then
        printf "{
        \"log\": {
        \"loglevel\": \"warning\",
        \"access\": \"/var/log/%s/access.log\",
        \"error\": \"/var/log/%s/error.log\"
        }
}
" $1 $1 > /usr/local/etc/$1/config.json
    fi
    #gen systemd service
    echo -e "\033[0;32mXray config location: /usr/local/etc/$1/config.json\033[0m"
    printf "[Unit]
Description=%s Service
After=network.target nss-lookup.target
[Service]
DynamicUser=yes
CapabilityBoundingSet=CAP_NET_ADMIN CAP_NET_BIND_SERVICE
AmbientCapabilities=CAP_NET_ADMIN CAP_NET_BIND_SERVICE
NoNewPrivileges=true
ExecStart=/usr/local/bin/%s run -config /usr/local/etc/%s/config.json
Restart=on-failure
RestartPreventExitStatus=23
LimitNOFILE=1048576000
LimitNPROC=10000
Environment=\"XRAY_LOCATION_ASSET=/usr/local/etc/$1\"
ReadWritePaths=/var/log/%s/
RestartSec=5s
[Install]
WantedBy=multi-user.target
" $1 $1 $1 $1 > /etc/systemd/system/$1.service
    systemctl daemon-reload
    systemctl disable $1.service --now
    systemctl enable $1.service --now
    echo -e "\033[0;32mXray systemd service location: /etc/systemd/system/$1.service\033[0m"
    rm -f $tempfiled
    rm -rf $tempfolderd
fi

#generate random reality config
if [[ $2 = "reality" ]]
then
    UUIDarray=()
    mycounter=0
    while (( $mycounter<10 ))
    do
        UUIDarray[mycounter]=`/usr/local/bin/$1 uuid`
        let "mycounter++"
    done
    # for i in ${UUIDarray[@]}
    # do
    #     echo "The value is: $i"
    # done
    output25519=$(/usr/local/bin/$1 x25519)
    private_key=$(echo "$output25519" | grep 'Private key:' | awk '{print $3}')
    public_key=$(echo "$output25519" | grep 'Public key:' | awk '{print $3}')
    echo $public_key > /usr/local/etc/$1/public.key
    echo -e "\033[0;32mpublic key is: "$public_key"\033[0m"
    echo -e "\033[0;32mprivate key is: "$private_key"\033[0m"
    shortIDarray=()
    mycounter=0
    while (( $mycounter<10 ))
    do
        shortIDarray[mycounter]=`/usr/local/bin/$1 uuid | cut -d '-' -f 4``/usr/local/bin/$1 uuid | cut -d '-' -f 5`
        let "mycounter++"
    done
    emailarray=()
    mycounter=0
    while (( $mycounter<10 ))
    do
        emailarray[mycounter]=`/usr/local/bin/$1 uuid | cut -d '-' -f 4`
        let "mycounter++"
    done
    while true
    do
        random_port=$((10000 + RANDOM % 55535))
        check_listen=`netstat -anp |grep -ai "listen" |grep -ai $random_port`
        if [[ $check_listen = "" ]]
        then
            echo -e "\033[0;32mSelecting random port $random_port\033[0m"
            break
        fi
    done
    printf "
{
    \"log\": {
      \"loglevel\": \"warning\",
      \"access\": \"/var/log/$1/access.log\",
      \"error\": \"/var/log/$1/error.log\"
    },
    \"inbounds\": [
        {
            \"tag\": \"native\",
            \"listen\": \"::\",
            \"port\": $random_port,
            \"protocol\": \"vless\",
            \"settings\": {
                \"clients\": [
                    {
                        \"id\": \"${UUIDarray[0]}\",
                        \"flow\": \"xtls-rprx-vision\",
                        \"email\": \"${emailarray[0]}@example.com\"
                    },
                    {
                        \"id\": \"${UUIDarray[1]}\",
                        \"flow\": \"xtls-rprx-vision\",
                        \"email\": \"${emailarray[1]}@example.com\"
                    },
                    {
                        \"id\": \"${UUIDarray[2]}\",
                        \"flow\": \"xtls-rprx-vision\",
                        \"email\": \"${emailarray[2]}@example.com\"
                    },
                    {
                        \"id\": \"${UUIDarray[3]}\",
                        \"flow\": \"xtls-rprx-vision\",
                        \"email\": \"${emailarray[3]}@example.com\"
                    },
                    {
                        \"id\": \"${UUIDarray[4]}\",
                        \"flow\": \"xtls-rprx-vision\",
                        \"email\": \"${emailarray[4]}@example.com\"
                    },
                    {
                        \"id\": \"${UUIDarray[5]}\",
                        \"flow\": \"xtls-rprx-vision\",
                        \"email\": \"${emailarray[5]}@example.com\"
                    },
                    {
                        \"id\": \"${UUIDarray[6]}\",
                        \"flow\": \"xtls-rprx-vision\",
                        \"email\": \"${emailarray[6]}@example.com\"
                    },
                    {
                        \"id\": \"${UUIDarray[7]}\",
                        \"flow\": \"xtls-rprx-vision\",
                        \"email\": \"${emailarray[7]}@example.com\"
                    },
                    {
                        \"id\": \"${UUIDarray[8]}\",
                        \"flow\": \"xtls-rprx-vision\",
                        \"email\": \"${emailarray[8]}@example.com\"
                    },
                    {
                        \"id\": \"${UUIDarray[9]}\",
                        \"flow\": \"xtls-rprx-vision\",
                        \"email\": \"${emailarray[9]}@example.com\"
                    }
                ],
                \"decryption\": \"none\"
            },
            \"streamSettings\": {
                \"network\": \"tcp\",
                \"security\": \"reality\",
                \"realitySettings\": {
                    \"dest\": \"www.doi.org:443\",
                    \"serverNames\": [
                        \"www.doi.org\"
                    ],
                    \"privateKey\": \"$private_key\",
                    \"minClientVer\": \"1.8.8\",
                    \"maxTimeDiff\": 3600000,
                    \"shortIds\": [
                        \"${shortIDarray[0]}\",
                        \"${shortIDarray[1]}\",
                        \"${shortIDarray[2]}\",
                        \"${shortIDarray[3]}\",
                        \"${shortIDarray[4]}\",
                        \"${shortIDarray[5]}\",
                        \"${shortIDarray[6]}\",
                        \"${shortIDarray[7]}\",
                        \"${shortIDarray[8]}\",
                        \"${shortIDarray[9]}\"
                    ]
                }
            },
            \"sniffing\": {
                \"enabled\": true,
                \"destOverride\": [
                    \"http\",
                    \"tls\"
                ],
                \"routeOnly\": true
            }
        }
    ],
    \"outbounds\": [
        {
            \"protocol\": \"freedom\",
            \"tag\": \"direct\"
        },
        {
            \"protocol\": \"blackhole\",
            \"tag\": \"block\"
        }
    ],
    \"routing\": {
        \"domainStrategy\": \"IPOnDemand\",
        \"rules\": [
            {
                \"type\": \"field\",
                \"inboundTag\": [
                    \"native\"
                ],
                \"user\":[
                    \"none@example.com\"
                ],
                \"outboundTag\": \"direct\"
            },
        {
            \"type\": \"field\",
            \"domain\": [
                \"geosite:cn\",
                \"ext:cnsite.dat:cn\"
            ],
            \"outboundTag\": \"block\"
        },
        {
            \"type\": \"field\",
            \"ip\": [
                \"geoip:cn\",
                \"ext:cn.dat:ipv4cn\",
                \"ext:cn.dat:ipv6cn\"
            ],
            \"outboundTag\": \"block\"
        },
        {
            \"type\": \"field\",
            \"inboundTag\": [
                \"native\"
            ],
            \"outboundTag\": \"direct\"
        }
        ]
    }
  }

" > /usr/local/etc/$1/config.json
    service $1 restart
    mycounter=0
    myip=`curl 4.ipw.cn` || myip=[`curl 6.ipw.cn`]
    while (( $mycounter<10 ))
    do
        echo -e "\033[0;32m  vless://${UUIDarray[$mycounter]}@$myip:$random_port?security=reality&encryption=none&pbk=$public_key&headerType=none&fp=safari&spx=%2Findex.html&type=tcp&flow=xtls-rprx-vision&sni=www.doi.org&sid=${shortIDarray[$mycounter]}#$myip  \033[0m"
        let "mycounter++"
    done

fi


