#!/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
sed -e 's/.*DefaultMemoryAccounting=.*/DefaultMemoryAccounting=yes/' -i /etc/systemd/system.conf
# cgroup tuning
echo "/opt/unetlab/scripts/remove-empty-cpu-cgroup.sh" > /sys/fs/cgroup/cpu/release_agent
echo "/opt/unetlab/scripts/remove-empty-memory-cgroup.sh" > /sys/fs/cgroup/memory/release_agent
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'"$BAREPARAMS"' "/g' /etc/default/grub &> /dev/null
sh -c 'echo "br_netfilter" > /etc/modules-load.d/br_netfilter.conf'
#Fix udev nbd
sed -i -e 's/nbd\*|//' /lib/udev/rules.d/60-block.rules &> /dev/null
#Fix udev hotplug for vun interfaces
sed -i -e 's/.*ifupdown-hotplug"/SUBSYSTEM=="net", KERNEL!="vunl*|vnet*", ACTION=="add|remove", RUN+="ifupdown-hotplug"/' /lib/udev/rules.d/80-ifupdown.rules  &> /dev/null
#tune #tune landscape
dpkg -s landscape-common > /dev/null 2>&1 
if [[ $? -eq 0 ]]; then
        echo landscape-common        landscape-common/sysinfo  select  "Do not display sysinfo on login" | debconf-set-selections
        dpkg-reconfigure -fnoninteractive landscape-common
fi
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 '
# nat device
auto natmac
    iface natmac inet manual
    pre-up ip link add natmac address 00:01:01:01:01:01 type dummy
auto nat0
iface nat0 inet static
    bridge_ports natmac 
    bridge_stp off
    address 10.0.137.254
    netmask 255.255.255.0
    up service udhcpd restart ' >>  /etc/network/interfaces ) &> /dev/null
echo -ne "Tuning nat interface... " 
grep -q natmac /etc/network/interfaces &> /dev/null
if [ $? -ne 0 ]; then
        sed -i -e  '/auto nat0/,/up service udhcpd restart/d' /etc/network/interfaces &> /dev/null
        ( echo 'auto natmac
iface natmac inet manual
    pre-up ip link add natmac address 00:01:01:01:01:01 type dummy
auto nat0
iface nat0 inet static
    bridge_ports natmac 
    bridge_stp off
    address 10.0.137.254
    netmask 255.255.255.0
    up service udhcpd restart ' >>  /etc/network/interfaces )  &> /dev/null
fi
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 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

# 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"
