#!/bin/bash
BASEDIR=$(dirname "$0")
echo -e " \033[0;32mbackup pnetlab databases to /opt/unetlab/database_backup/\033[0m"
unl_wrapper -a backupdb  &> /dev/null

function set_yml_template_folder_location() {
data=$(mysql -uroot -ppnetlab -D pnetlab_db -e "SELECT control_value FROM control WHERE control_value>1;" 2>/dev/null)
data_array=($data)
pnetlab_version=${data_array[1]}
if [[ $pnetlab_version == "4.2.10" ]] || [[ $pnetlab_version == "5.0.1" ]]; then
                echo -e " \033[0;32mbackup templates user for [4.2.10] [5.0.1] to /opt/unetlab/html/templates/backup_templates/backup_templates_user/\033[0m"
                mkdir  /opt/unetlab/html/templates/intel &> /dev/null
                mkdir  /opt/unetlab/html/templates/amd  &> /dev/null
                mkdir -p /opt/unetlab/html/templates/backup_templates/backup_templates_user  &> /dev/null
                cp /opt/unetlab/html/templates/*.yml /opt/unetlab/html/templates/backup_templates/backup_templates_user/ &> /dev/null
                for i in /opt/unetlab/html/templates/*.yml ;
                do cp $i /opt/unetlab/html/templates/intel/  &> /dev/null
                mv $i /opt/unetlab/html/templates/amd/  &> /dev/null
                done
fi
if [[ $pnetlab_version == *5.2* ]] || [[ $pnetlab_version == *5.3* ]] || [[ $pnetlab_version == *6.* ]]; then
                echo -e " \033[0;32mbackup templates user for [5.3.*] [5.2.*] to /opt/unetlab/html/templates/templates_5.x/\033[0m"
                mkdir -p /opt/unetlab/html/templates/backup_templates/templates_5.x/intel &> /dev/null
                mkdir -p /opt/unetlab/html/templates/backup_templates/templates_5.x/amd &> /dev/null
                cp /opt/unetlab/html/templates/intel/*.yml /opt/unetlab/html/templates/backup_templates/templates_5.x/intel   &> /dev/null
                cp /opt/unetlab/html/templates/amd/*.yml /opt/unetlab/html/templates/backup_templates/templates_5.x/amd  &> /dev/null
fi
}
set_yml_template_folder_location 
for i in /opt/unetlab/scripts/config_* 
        do mv $i /opt/unetlab/config_scripts/backup_scripts/  &> /dev/null
done
cp -Rf $BASEDIR/system_files/opt / &> /dev/null
cp -Rf $BASEDIR/system_files/usr / &> /dev/null
rm /etc/default/udhcpd &> /dev/null
rm /etc/init.d/udhcpd &> /dev/null
rm /etc/udhcpd.conf &> /dev/null
sed -i '/i-share.top/d' /etc/apt/sources.list &> /dev/null
sed -i 's/"storage-driver": "aufs"/"storage-driver": "overlay2"/g' /etc/docker/daemon.json &> /dev/null
rm -rf /var/lib/docker/aufs  &> /dev/null
rm -rf /opt/unetlab/html/themes/adminLTE  &> /dev/null
apt-get update
MISSING=$(dpkg --get-selections udhcpd  resolvconf linux-image-4.20.17.2-eve-ng-uksm-wg+ linux-headers-4.20.17.2-eve-ng-uksm-wg+  2>&1 | grep -v 'install$' | awk '{ print $6 }') &> /dev/null
sudo apt-get install $MISSING docker.io
DEBIAN_FRONTEND=noninteractive apt-get -y install docker.io $MISSING  &> /dev/null
DEBIAN_FRONTEND=noninteractive apt-get -y install --reinstall pnetlab-docker &> /dev/null
touch /var/lib/misc/udhcpd.leases &> /dev/null 2>&1
chmod 755 /opt/unetlab/wrappers/* > /dev/null 2>&1
BAREPARAMS=$(cat /etc/default/BAREPARAMS 2>/dev/null || true ) &> /dev/null
sed -i 's/.*GRUB_CMDLINE_LINUX_DEFAULT=.*/GRUB_CMDLINE_LINUX_DEFAULT="net.ifnames=0 quiet splash vga=788 apparmor=0"/g' /etc/default/grub &> /dev/null
sed -i 's/.*GRUB_GFXMODE=.*/GRUB_GFXMODE="800x600"/g' /etc/default/grub &> /dev/null
sed -i 's/.*GRUB_HIDDEN_TIMEOUT=.*/GRUB_HIDDEN_TIMEOUT=2/g' /etc/default/grub &> /dev/null
sed -i 's/.*GRUB_HIDDEN_TIMEOUT_QUIET=.*/GRUB_HIDDEN_TIMEOUT_QUIET=true/g' /etc/default/grub &> /dev/null
sed -i 's/.*GRUB_TIMEOUT=.*/GRUB_TIMEOUT=0/g' /etc/default/grub &> /dev/null
sed -i 's/.*GRUB_CMDLINE_LINUX=.*/GRUB_CMDLINE_LINUX="net.ifnames=0 mitigations=off pti=off spectre_v2=off nopti l1tf=off nospec_store_bypass_disable no_stf_barrier mitigations=off'"$BAREPARAMS"' "/g' /etc/default/grub &> /dev/null
sh -c 'echo "br_netfilter" > /etc/modules-load.d/br_netfilter.conf'
sed -i 's/#net.ipv4.ip_forward=1/net.ipv4.ip_forward=1/' /etc/sysctl.conf &> /dev/null
systemctl disable pnetnat &> /dev/null
rm /opt/unetlab/html/store/app/Console/Commands/pnetnat &> /dev/null
sysctl -w net.ipv6.conf.all.disable_ipv6=1  &> /dev/null
pkill  dnsmasq &> /dev/null
ip link delete pnet_nat &> /dev/null
sed -i 's/138/137/g' /etc/network/interfaces &> /dev/null
sed -i 's/pnet_nat/nat0/g' /etc/network/interfaces &> /dev/null
fgrep -q pnet0 /etc/network/interfaces && ( fgrep -q nat0 /etc/network/interfaces  || echo '
# nat0 device
auto nat0
iface nat0 inet static
    bridge_ports none 
    bridge_stp off
    address 10.0.137.254
    netmask 255.255.255.0
    up service udhcpd restart ' >>  /etc/network/interfaces ) &> /dev/null
sed -i -e '/^PrivateTmp/d' /lib/systemd/system/apache2.service  &> /dev/null
echo 'nameserver 8.8.8.8' >> /etc/resolvconf/resolv.conf.d/head  &> /dev/null
echo 'nameserver 1.1.1.1' >> /etc/resolvconf/resolv.conf.d/head &> /dev/null
sed -e 's/.*DefaultTimeoutStopSec=.*/DefaultTimeoutStopSec=5s/' -i /etc/systemd/system.conf
systemctl disable systemd-resolved.service &> /dev/null && systemctl disable resolvconf-pull-resolved.service  &> /dev/null
if [  ! -e /opt/unetlab/addons/iol/bin/iourc ] ; then \
license=$(python2 /opt/unetlab/addons/iol/bin/CiscoIOUKeygen.py | grep "=" | grep -v "hostname") && echo -e "[license]\n$license" > /opt/unetlab/addons/iol/bin/iourc
fi
resolvconf -u &> /dev/null
cp -Rf $BASEDIR/system_files/etc / &> /dev/null
systemctl daemon-reload &> /dev/null
systemctl enable udhcpd &> /dev/null
service apache2 restart &> /dev/null
service docker restart &> /dev/null
service ovfstartup restart &> /dev/null
sed -i 's/.*::.*//' /etc/hosts &> /dev/null
for i in /sys/class/net/pnet*/bridge/group_fwd_mask  ; do echo 8 > $i ; done
grep -q default_time_zone /etc/mysql/mysql.conf.d/mysqld.cnf  &> /dev/null
if [ $? -ne 0 ]; then
    echo "default_time_zone='+00:00'" >> /etc/mysql/mysql.conf.d/mysqld.cnf
    systemctl restart mysql &> /dev/null
fi
grep -q innodb_flush_log_at_trx_commit /etc/mysql/mysql.conf.d/mysqld.cnf  &> /dev/null
if [ $? -ne 0 ]; then
        echo "innodb_flush_log_at_trx_commit = 2 " >> /etc/mysql/mysql.conf.d/mysqld.cnf
        systemctl restart mysql &> /dev/null
fi
grep -q max_connections /etc/mysql/mysql.conf.d/mysqld.cnf  &> /dev/null
if [ $? -ne 0 ]; then
        echo "max_connections=250" >> /etc/mysql/mysql.conf.d/mysqld.cnf
        systemctl restart mysql &> /dev/null
fi

grep -q skip_ssl /etc/mysql/mysql.conf.d/mysqld.cnf  &> /dev/null
if [ $? -ne 0 ]; then
        echo "skip_ssl" >> /etc/mysql/mysql.conf.d/mysqld.cnf
        systemctl restart mysql &> /dev/null
fi
# GCP 
gcp_tune () {
sed -i '/\iface pnet0 inet dhcp/a pre-up ip link set dev eth0 up' /etc/network/interfaces  &> /dev/null
cd /sys/class/net/; for i in ens* ; do echo 'SUBSYSTEM=="net", ACTION=="add", DRIVERS=="?*", ATTR{address}=="'$(cat $i/address)'", ATTR{type}=="1", KERNEL=="ens*", NAME="'$i'"' ; done  > /etc/udev/rules.d/70-persistent-net.rules
sed -i -e 's/NAME="ens.*/NAME="eth0"/' /etc/udev/rules.d/70-persistent-net.rules
sed -i -e 's/ens4/eth0/' /etc/netplan/50-cloud-init.yaml
sed -i -e 's/PasswordAuthentication.*/PasswordAuthentication yes/' /etc/ssh/sshd_config
apt-mark hold linux-image-gcp
mv /boot/vmlinuz-*gcp /root
update-grub2
}
dmidecode  -t bios | grep -q Google  && gcp_tune
# Detect PLatform
systemd-detect-virt -v > /opt/unetlab/hypervisor
echo -ne "Platform detection and tuning "
fgrep -e vmx -e svm /proc/cpuinfo 
if [[ $? -eq 0 ]]; then
grep -q vmx /proc/cpuinfo && echo -n vmx > /opt/unetlab/platform
grep -q svm /proc/cpuinfo && echo -n svm > /opt/unetlab/platform
fi
while read line
do
        my_array=("${my_array[@]}" $line)
done <<< $a
for (( i=${#my_array[@]} - 1; i >= 0; i-- )) ; do
        newname=$(echo ${my_array[i]} | sed -e 's/\%2E$/./')
        newname=$(echo $newname | sed -e 's/\%2A$/*/')
        mv "${my_array[i]}" "$newname"
done
sysctl -p  &> /dev/null
/opt/unetlab/wrappers/unl_wrapper -a fixpermissions  2>/dev/null
update-grub && update-grub2  &> /dev/null
rm -rf /root/upgrade &> /dev/null && rm /root/5.* &> /dev/null
rm  /opt/unetlab/html/devices/qemu/device_win.php &> /dev/null  
rm  /opt/unetlab/html/devices/qemu/device_winserver.php  &> /dev/null 
rm  /opt/unetlab/html/devices/qemu/device_linux.php &> /dev/null
version=$(cat /opt/unetlab/version)
if [ -e /opt/unetlab/version ] ; then \
mysql -uroot -ppnetlab -D pnetlab_db -e "replace control (control_name, control_value) values ('ctrl_version','$version')" 2>/dev/null
fi
mysql -uroot -ppnetlab -D pnetlab_db -e "delete from process where process_id='upgrade'" 2>/dev/null
/opt/unetlab/wrappers/unl_wrapper -a fixpermissions  
service networking restart 
echo -e "\033[0;32mUpgraded successfully to $version\033[0m"
