#!/bin/bash

def_port=8080;
def_uuid="abaa28c4-1add-428c-e8ce-bc75bca1b50a"
url="https://cdn.udinweb.com/xray/sync.txt"


function validate_url(){
  if [[ `wget -S --spider $1  2>&1 | grep 'HTTP/1.1 200 OK'` ]]; then
    return 0
  else
    return 1
  fi
}

if [ "$(curl -s "$url")" != "1" ] && [ $# -eq 0 ] ; then
    exit 1
fi

if [[ $(cat /etc/*-release | grep "Ubuntu") ]]; then

    read -p "Please Enter The Port[$def_port]:" port
    if [ -z "$port" ]; then
        port="$def_port"
    fi
    read -p "Please Enter The UUID[$def_uuid]:" uuid
    if [ -z "$uuid" ]; then
        uuid="$def_uuid"
    fi
    
    if [ -z "$(command -v xray)" ]; then
        bash -c "$(curl -L https://github.com/XTLS/Xray-install/raw/main/install-release.sh)" @ install -u root
        systemctl enable xray
    fi
    cd /usr/local/etc/xray
    systemctl stop xray
    rm -rf *
    endpoint="https://cdn.udinweb.com/xray/$1"
    if validate_url $endpoint && [ ! -z "${1// }" ];then
        wget -O "config.json" "$endpoint"
      else
        wget https://cdn.udinweb.com/xray/config.json
    fi
    sed -i "s|PORT|$port|g" config.json
    sed -i "s|UUID|$uuid|g" config.json
    systemctl restart xray
    echo "Xray Install And Configured Successfully!"
else
    echo "This should only be run on ubuntu\n";
    exit 1;
fi