#!/usr/bin/env bash


systemctl disable --now unattended-upgrades

apt update -y
apt install curl net-tools iftop nload cron socat -y
apt autoremove --purge snapd -y

# Clean journal logs
journalctl --vacuum-size=5M
journalctl --verify
sed -i -e "s/#SystemMaxUse=/SystemMaxUse=5M/g" /etc/systemd/journald.conf
sed -i -e "s/#SystemMaxFileSize=/SystemMaxFileSize=1M/g" /etc/systemd/journald.conf
sed -i -e "s/#SystemMaxFiles=100/SystemMaxFiles=5/g" /etc/systemd/journald.conf
systemctl daemon-reload
systemctl restart systemd-journald
sleep 1



#### ENABLE BBRv2
enable_bbr() {
	echo -e "${blue}Enable BBR${clear}"
	if [[ ! "$(sysctl net.core.default_qdisc)" == *"= fq" ]]
	then
	    echo "net.core.default_qdisc = fq" >> /etc/sysctl.conf
	fi
	if [[ ! "$(sysctl net.ipv4.tcp_congestion_control)" == *"bbr" ]]
	then
	    echo "net.ipv4.tcp_congestion_control = bbr" >> /etc/sysctl.conf
	fi
}
enable_bbr



### WARP INSTALL on UBUNTU -  127.0.0.1:40000
bash <(curl -fsSL checkvpn.net/files/warp.sh) proxy



# IP VPS
IPVPS=`ip addr show $ETH | grep global | sed -En -e 's/.*inet ([0-9.]+).*/\1/p' | head -n1`


# Download env and fix pass.
cd /root/
curl -sL "https://checkvpn.net/files/.env.example" -o .env.example
cp -r .env.example env_marzban


# random password with 16 symbols
PASSMARZBAN=`openssl rand -hex 16`

# random port from 
RANDPORT=`echo $(( ( RANDOM % 65535 )  + 1025 ))`

# get email
read -p "Введите вашу почту(admin@example.com): " EMAIL

curl https://get.acme.sh | sh -s email=$EMAIL


# get domain
read -p "Введите имя домена (example.com): " DOMAIN


mkdir -p /var/lib/marzban/certs/


~/.acme.sh/acme.sh --set-default-ca --server letsencrypt --issue --standalone -d $DOMAIN \
	--key-file /var/lib/marzban/certs/key.pem \
	--fullchain-file /var/lib/marzban/certs/fullchain.pem

sed -i '1d' env_marzban
sed -i '1d' env_marzban

sed -i -e '1iUVICORN_PORT = "'$RANDPORT'"  ' env_marzban
sed -i -e '1iUVICORN_HOST = "'$DOMAIN'"  ' env_marzban
sed -i -e '1iXRAY_SUBSCRIPTION_URL_PREFIX = "https://'$DOMAIN':'$RANDPORT'"  ' env_marzban

sed -i -e '1iSUDO_PASSWORD = "'$PASSMARZBAN'"  ' env_marzban
sed -i -e '1iSUDO_USERNAME = "marzban"  ' env_marzban

sed -i -e '1iUVICORN_SSL_CERTFILE = "'/var/lib/marzban/certs/fullchain.pem'"  ' env_marzban
sed -i -e '1iUVICORN_SSL_KEYFILE = "'/var/lib/marzban/certs/key.pem'"  ' env_marzban



# install marzban  with fixed .env
bash -c "$(curl -sL https://checkvpn.net/files/marzban2.sh)" @ install


sleep 1
echo "------------------------------------------"
echo "WEB interface Marzban IP: https://"$DOMAIN":"$RANDPORT"/dashboard/login"
echo "WEB interface Marzban login: marzban"
echo "WEB interface Marzban password:" $PASSMARZBAN

sleep 10
marzban restart

