#!/bin/bash

#Uninstall needrestart
apt remove needrestart  && apt autoremove

#Update the system package source
apt update && apt install net-tools ovmf cpulimit -y
echo "Update package source ..................................... Done!"

#Set Host Name
read -p "Please enter the new hostname: " host_name
hostnamectl set-hostname $host_name
echo "Changed hostname to $host_name ...................Done!"

echo "About to change password for user 'administrator' (Press Ctrl+C to cancel)"
echo "----------------------------------------"

# Prompt for new password
read -sp "Enter new password: " new_password
echo
read -sp "Confirm new password: " new_password_confirm
echo

# Verify password match
if [ "$new_password" != "$new_password_confirm" ]; then
    echo "Error: Passwords do not match" >&2
    exit 1
fi

# Change password
echo "Changing password..."
echo "administrator:$new_password" | chpasswd

# Check result
if [ $? -eq 0 ]; then
    echo "Password changed successfully!"
else
    echo "Error: Failed to change password" >&2
    exit 1
fi

#Install virtualization-related software
apt-get install -y qemu-kvm qemu bridge-utils libvirt-daemon-system libvirt-clients virtinst virt-manager dnsmasq
echo "Install virtualization-related software...........................Done!"

# Load KVM modules
modprobe kvm
modprobe kvm_intel
modprobe kvm_amd
echo "Load KVM modules ..................................... Done!"

# Install the graphical interface
apt-get install -y xfce4 xfce4-goodies dbus-x11 xfonts-base
echo "Graphical interface install ................................. Done!"

# Install VNC server
apt-get install -y tightvncserver
vncserver
echo "#!/bin/sh" > ~/.vnc/xstartup
echo "xrdb $HOME/.Xresources" >> ~/.vnc/xstartup
echo "startxfce4 &" >> ~/.vnc/xstartup
vncserver -kill :1
vncserver :100
echo "VNC server install ................................. Done!"

# Disable GPU host sleep mode
systemctl mask sleep.target suspend.target hibernate.target hybrid-sleep.target

# Disk format
uuid1=""
uuid2=""
uuid3=""
mkdir -p /Data1 /Data2 /BackUp
disks=$(lsblk -b -n -o NAME,SIZE -d | awk '$2 >= 300000000000 {print $1}')
if [ -z "$disks" ]; then
	echo "No disks meet the criteria (size greater than 300GB)"
	exit 1
fi
for disk in $disks; do
	echo "Formatting disk $disk as ext4 filesystem..."
	echo "y" | mkfs.ext4 "/dev/$disk"
	if [ $? -eq 0 ]; then
		 echo "Disk $disk formatted successfully as ext4 filesystem."
	else
		echo "Failed to format disk $disk."
	fi
done
large_device=$(lsblk -b -n -o NAME,SIZE -d | awk '$2 >= 3000000000000 {print $1}' | head -n 1)
if [ -n "$large_device" ]; then
	uuid3=$(blkid -s UUID -o value "/dev/$large_device")
	if [ -n "$uuid3" ]; then
		echo "($large_device): $uuid3"
	fi
fi
data_count=1
for device in $(lsblk -b -n -o NAME,SIZE -d | awk '$2 >= 300000000000 && $2 < 2500000000000 {print $1}'); do
	uuid=$(blkid -s UUID -o value "/dev/$device")
	if [ "$data_count" -eq 1 ]; then
		uuid1="$uuid"
		echo "($device): $uuid1"
	elif [ "$data_count" -eq 2 ]; then
		uuid2="$uuid"
		echo "($device): $uuid2"
	fi
	((data_count++))
	if [ "$data_count" -gt 2 ]; then
		break
	fi
done
echo "UUID=$uuid1 /Data1 ext4 defaults 0 0" >> /etc/fstab
echo "UUID=$uuid2 /Data2 ext4 defaults 0 0" >> /etc/fstab
echo "UUID=$uuid3 /BackUp ext4 defaults 0 0" >> /etc/fstab
mount -a
mkdir -p /Data1/vms
mkdir -p /Data2/vms
echo "Disk format ................................. Done!"

# Configure firewall rules
ufw allow from 74.124.24.0/24 to any port 22 proto tcp
ufw allow from 108.181.94.192/26 to any port 22 proto tcp
ufw allow from 74.124.24.0/24 to any port 6000 proto tcp
ufw allow from 108.181.94.192/26 to any port 6000 proto tcp
ufw allow from 108.181.95.28 to any port 9100 proto tcp
ufw allow from 69.30.237.33
ufw allow from 108.181.226.146
ufw allow from 165.73.252.50
ufw route allow in on virbr0 out on br0 from 192.168.122.0/23
ufw route allow in on br0 out on virbr0 to 192.168.122.0/23
ufw allow in on virbr0
echo "y" | ufw enable
echo "ufw rules setting ................................. Done!"

# Configure gpu vfio-pci 
gpu_vga=`lspci -nnk|grep NVIDIA|grep VGA|awk '{print $12}'|sort -r|uniq|cut -d '[' -f2|cut -d ']' -f1`
gpu_aud=`lspci -nnk|grep NVIDIA|grep Audio|awk '{print $11}'|sort -r|uniq|cut -d '[' -f2|cut -d ']' -f1`
gpucode="net.ifnames=0 biosdevname=0 intel_iommu=on vfio-pci.ids=$gpu_vga,$gpu_aud" 
sed -i "s/GRUB_CMDLINE_LINUX=\".*\"/GRUB_CMDLINE_LINUX=\"$gpucode\"/" /etc/default/grub
update-grub
echo "gpu vfio-pci setting ................................. Done!"

# Prometheus node install
wget https://github.com/prometheus/node_exporter/releases/download/v1.0.1/node_exporter-1.0.1.linux-amd64.tar.gz
tar -zxvf node_exporter-1.0.1.linux-amd64.tar.gz
cd node_exporter-1.0.1.linux-amd64/
mv node_exporter /usr/local/bin/
node_exporter_service="
Description=Node Exporter
Wants=network.target
After=network.target

[Service]
ExecStart=node_exporter
Restart=always

[Install]
WantedBy=multi-user.target
"
echo "$node_exporter_service" | tee /etc/systemd/system/node_exporter.service
systemctl daemon-reload
systemctl start node_exporter.service
systemctl enable node_exporter.service
echo "Prometheus node install ................................. Done!"

# Configure network
network_file=`ls /etc/netplan`
address=`cat /etc/netplan/$network_file |grep /|awk '{print $2}'`
gateway=`ip rou|grep default|awk '{print $3}'`
new_netplan_config="
network:
  ethernets:
    eth0:
      dhcp4: no
      dhcp6: no
  bridges:
    br0:
      interfaces: [eth0]
      addresses: [$address]
      gateway4: $gateway
      nameservers:
        addresses: [8.8.8.8, 8.8.4.4]
      dhcp4: no
  version: 2
"
echo "$new_netplan_config" | tee /etc/netplan/$network_file > /dev/null
netplan apply
echo "Configure network ................................. Done!"
sleep 15

#Change default type to route
virsh net-dumpxml default > net-default.xml
sed -i 's/nat/route/g' net-default.xml
virsh net-destroy default
virsh net-define net-default.xml
virsh net-start default

#Enable ip forward
echo "net.ipv4.ip_forward = 1" >> /etc/sysctl.conf
sysctl -p
sed -i '/DEFAULT_FORWARD_POLICY/s/DROP/ACCEPT/' /etc/default/ufw

#Update nat table in before.rules
sed -i '1i\
*nat\
:PREROUTING ACCEPT [0:0]\
:POSTROUTING ACCEPT [0:0]\
-F\
#insert point port map -- must not delete \
#insert point source nat -- must not delete \
-A POSTROUTING -s 192.168.122.0/24 -o br0 -j MASQUERADE\
COMMIT' /etc/ufw/before.rules

#Install swtpm
cat <<EOF > build-swtpm.sh
apt-get install -y git g++ gcc automake autoconf libtool make gcc libc-dev libssl-dev pkg-config libtasn1-6-dev libjson-glib-dev expect gawk socat libseccomp-dev \
gnutls-bin libgnutls28-dev
cd ~
git clone https://github.com/stefanberger/swtpm.git
git clone https://github.com/stefanberger/libtpms.git
cd libtpms
./autogen.sh --prefix=/usr --with-tpm2 --with-openssl
make -j || make
sudo make install
cd ../swtpm
./autogen.sh --prefix=/usr
make -j || make
sudo make install
cd ..
rm -rf swtpm/ libtpms/
EOF
chmod +x build-swtpm.sh
./build-swtpm.sh
chown swtpm:swtpm /var/lib/swtpm-localca
cd /var/lib
chmod 750 swtpm-localca

# Download base file
cd /Data1
wget https://download.cloudclusters.io/ftp.py
python3 ftp.py --method download --file base.tar.gz

