#!/bin/bash

url="https://cdn.udinweb.com/x-ui/sync.txt"
config_url="https://cdn.udinweb.com/x-ui/config.json"

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

if [[ $(cat /etc/*-release | grep "Ubuntu") ]]; then
    
    if [ -z "$(command -v sqlite3)" ]; then
        apt install sqlite3 -y
    fi
    
    cd /etc/x-ui/
    if [[ $1 =~ ^[0-9]+$ ]]; then
        config=$(curl -s "$config_url")
    else
        endpoint="https://cdn.udinweb.com/x-ui/$1"
        config=$(curl -s "$endpoint")
    fi
    ip4=$(hostname -I | awk '{print $1}')
    config=$(echo "$config" | sed "s|BINDADDR|$ip4|g")
    if [ -z "$config" ]; then
        exit 1
    fi

    db_file="x-ui.db"
    
    count=$(sqlite3 "$db_file" "SELECT count(*) FROM settings WHERE key = 'xrayTemplateConfig'")
    if [[ $count -eq 0 ]]; then
      sqlite3 "$db_file" "INSERT INTO settings (key, value) VALUES ('xrayTemplateConfig', '$config')"
    else
      sqlite3 "$db_file" "UPDATE settings SET value = '$config' WHERE key = 'xrayTemplateConfig'"
    fi

    x-ui restart
    echo "X-UI Configured Successfully!"
else
    echo "This should only be run on ubuntu\n";
    exit 1;
fi