#!/bin/bash
interface1=`ls /sys/class/net | sed -n '1p'`
interface2=`ls /sys/class/net | sed -n '2p'`
script_name=`echo ${0##*/} | cut -d'.' -f1`
default_log_file_name=`echo $script_name.log`
log_file=${4:-$default_log_file_name}
backup_dir=/opt/backup_cfg
san_repo="deb [arch=amd64 trusted=yes] http://repo.starwind.com/san-and-nas/ focal main"
NORMAL='\033[0m'
RED='\033[31m'
GREEN='\033[32m'
BOLD='\033[1m'


function check_version {
if ! [ -f /opt/starwind/starwind-san-and-nas-console/VSAManagementConsole.dll ];
  then
       version="$(strings /opt/VSAManagementConsole/VSAManagementConsole.dll | egrep '^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$' | cut -d '.' -f1,2)"
          echo -e "${GREEN}${BOLD}Update required. Current version: ${version}${NORMAL}"
          return 1
  else
        version="$(strings /opt/starwind/starwind-san-and-nas-console/VSAManagementConsole.dll | egrep '^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$' | cut -d '.' -f1,2)"
          if [ "$version" == "1.2" ]
            then
              echo -e "${GREEN}${BOLD}No update required. Current version: ${version}${NORMAL}"
              exit 1
          fi
fi
}

check_version

echo -e "${BOLD}${RED}WARNING:${NORMAL}${BOLD} Before performing the update, you must disconnect all active ISCSI connections!${NORMAL}"

echo -ne "${BOLD}${GREEN} Are all connections disabled? (y/N) ${NORMAL}"

read item
case "$item" in
        y|Y) if [[ $UID != 0 ]]; then echo "You mast to have root privileges to run this script."; echo "Try to run: sudo $0 $*"; exit 1; fi

function print_and_log {
echo -e $1 | tee -a $log_file
}

print_and_log "${BOLD}Stoping services:${NORMAL}"
print_and_log "${BOLD}#########################################################################${NORMAL}"

function stop_service {
print_and_log 'Trying to stop service: '$1
systemctl stop $1
if [[ $? -ne 0 ]]
then
   print_and_log "${RED}Can not stop Service.${NORMAL}"
   print_and_log "${RED}Please stop service manually and start this script again. Or contact with StarWind support team.${NORMAL}"
   return 3
else
   print_and_log "${GREEN}Service stopped succesfuly.${NORMAL}"
   return 0
fi
}

stop_service PerformanceDataService.service
if [ "$?" -ne 0 ]; then exit 1; fi

stop_service StarWindHealth.service
if [ "$?" -ne 0 ]; then exit 1; fi

stop_service StarWindVSA.service
if [ "$?" -ne 0 ]; then exit 1; fi

stop_service TelegrafMetricsStore.service
if [ "$?" -ne 0 ]; then exit 1; fi

stop_service StarWindvCenterPlugin.service
if [ "$?" -ne 0 ]; then exit 1; fi

stop_service aerospike.service
if [ "$?" -ne 0 ]; then exit 1; fi

stop_service getty@tty1.service
if [ "$?" -ne 0 ]; then exit 1; fi

stop_service getty@tty2.service
if [ "$?" -ne 0 ]; then exit 1; fi

print_and_log "${BOLD}Checking services is active:${NORMAL}"
print_and_log "${BOLD}#########################################################################${NORMAL}"

function check_service {
print_and_log 'Checking services is active: '$1 
systemctl is-active $1
   if [[ $? = active ]]
   then
      print_and_log "${RED}Service is active. Can not continue the process.${NORMAL}"
      print_and_log "${RED}Please stop service manually and start this script again. Or contact with StarWind support team.${NORMAL}"
	  exit 1
   else
      print_and_log "${GREEN}Service is not active. Continue the process.${NORMAL}"
   fi
}

function check_isci {
if grep -q $1 /etc/fstab
  then print_and_log "${GREEN}Unmouting $1.${NORMAL}"
       umount /mnt/$1
  else print_and_log "${GREEN}$1 is disconnect.${NORMAL}"
fi
}

check_service PerformanceDataService.service
if [ "$?" -ne 0 ]; then exit 2; fi

check_service StarWindHealth.service
if [ "$?" -ne 0 ]; then exit 2; fi

check_service StarWindVSA.service
if [ "$?" -ne 0 ]; then exit 2; fi

check_service TelegrafMetricsStore.service
if [ "$?" -ne 0 ]; then exit 2; fi

check_service StarWindvCenterPlugin.service
if [ "$?" -ne 0 ]; then exit 2; fi

check_service aerospike.service
if [ "$?" -ne 0 ]; then exit 2; fi


check_isci mdadm*
if [ "$?" -ne 0 ]; then exit 2; fi

check_isci zfs*/*
if [ "$?" -ne 0 ]; then exit 2; fi

cp /etc/fstab /etc/fstab.backup
if [ "$?" -ne 0 ]; then exit 2; fi

sed -i 's/nofail,//g' /etc/fstab
if [ "$?" -ne 0 ]; then exit 2; fi

print_and_log "${BOLD}Copy files:${NORMAL}"
print_and_log "${BOLD}#########################################################################${NORMAL}"

mkdir -p $backup_dir/PerformanceDataService
mkdir -p $backup_dir/StarWindVSA
mkdir -p $backup_dir/VSAManagementConsole
mkdir -p $backup_dir/TelegrafMetricsStore
mkdir -p $backup_dir/StarWindvCenterPlugin

function copy_files {
print_and_log "Copy files to templorary folder"
cp -rf $1 $backup_dir/$2 2> >(tee >(cat >> $log_file))
if [[ $? -ne 0 ]]
then
   print_and_log "${RED}Can not copy files.${NORMAL}"
   return 4
else
   print_and_log "${GREEN}Files copied succesfuly.${NORMAL}"
fi
}

copy_files "/opt/PerformanceDataService/StarStack.db" "PerformanceDataService"
if [ "$?" -ne 0 ]; then exit 3; fi

copy_files "/opt/StarWind/StarWindVSA/drive_c/StarWind/events" "StarWindVSA"
if [ "$?" -ne 0 ]; then exit 3; fi

copy_files "/opt/StarWind/StarWindVSA/drive_c/StarWind/NotifyDB" "StarWindVSA"
if [ "$?" -ne 0 ]; then exit 3; fi

copy_files "/opt/StarWind/StarWindVSA/drive_c/StarWind/PerformanceDB" "StarWindVSA"
if [ "$?" -ne 0 ]; then exit 3; fi

copy_files "/opt/StarWind/StarWindVSA/drive_c/StarWind/StarWind.cfg" "StarWindVSA"
if [ "$?" -ne 0 ]; then exit 3; fi

copy_files "/opt/StarWind/StarWindVSA/system.reg" "StarWindVSA"
if [ "$?" -ne 0 ]; then exit 3; fi

copy_files "/opt/TelegrafMetricsStore/StarStack.db" "TelegrafMetricsStore"
if [ "$?" -ne 0 ]; then exit 3; fi

copy_files "/opt/StarWind.vCenterPlugin/StarStack.db" "StarWindvCenterPlugin"
if [ "$?" -ne 0 ]; then exit 3; fi

copy_files "/opt/VSAManagementConsole/VSAManagementConsole.db" "VSAManagementConsole"
if [ "$?" -ne 0 ]; then exit 3; fi

copy_files "/opt/VSAManagementConsole/ccsdlocal" "VSAManagementConsole"
if [ "$?" -ne 0 ]; then exit 3; fi

print_and_log "${BOLD}Uninstall services:${NORMAL}"
print_and_log "${BOLD}#########################################################################${NORMAL}"


function remove_service {
print_and_log "Remove $1"
apt purge -y $1
if [[ $? -ne 0 ]]
then
   print_and_log "${RED}Can not remove $1 Service.${NORMAL}"
   print_and_log "${RED}Please remove service manually and start this script again. Or contact with StarWind support team.${NORMAL}"
   return 3
else
   print_and_log "${GREEN}Remove $1 succesfuly.${NORMAL}"
   return 0
fi
}

remove_service vsaperformancedataservice
if [ "$?" -ne 0 ]; then exit 4; fi

remove_service starwindvsa
if [ "$?" -ne 0 ]; then exit 4; fi

remove_service vsatelegrafmetricsstore
if [ "$?" -ne 0 ]; then exit 4; fi

remove_service vsamanagementconsole
if [ "$?" -ne 0 ]; then exit 4; fi

remove_service starwindvcenterplugin
if [ "$?" -ne 0 ]; then exit 4; fi

rm -rf /opt/PerformanceDataService
if [ "$?" -ne 0 ]; then exit 4; fi

rm -rf /opt/StarWind
if [ "$?" -ne 0 ]; then exit 4; fi

rm -rf /opt/TelegrafMetricsStore
if [ "$?" -ne 0 ]; then exit 4; fi

rm -rf /opt/StarWind.vCenterPlugin
if [ "$?" -ne 0 ]; then exit 4; fi

rm -rf /opt/VSAManagementConsole
if [ "$?" -ne 0 ]; then exit 4; fi

rm -rf /opt/StarWind/StarWindHealth
rm -rf /var/StarWind/StarWindHealth
rm -f /etc/StarWindHealth.conf 
rm -f /etc/systemd/system/StarWindHealth.service
rm -f /etc/cron.daily/CertificateReNew.sh
rm -rf /var/log/starstack
rm -rf /var/log/StarWind
rm -rf /var/log/VSAManagementConsole

print_and_log "${BOLD}Preparing for installation starwind-san-and-nas:${NORMAL}"
print_and_log "${BOLD}#########################################################################${NORMAL}"

wget https://dl.dell.com/FOLDER07815522M/1/PERCCLI_7.1910.00_A12_Linux.tar.gz
if [ "$?" -ne 0 ]; then exit 5; fi

tar -zxvf PERCCLI_7.1910.00_A12_Linux.tar.gz
if [ "$?" -ne 0 ]; then exit 5; fi

dpkg -i PERCCLI_7.1910.00_A12_Linux/perccli_007.1910.0000.0000_all.deb
if [ "$?" -ne 0 ]; then exit 5; fi

wget https://nginx.org/keys/nginx_signing.key
if [ "$?" -ne 0 ]; then exit 5; fi

apt-key add nginx_signing.key
if [ "$?" -ne 0 ]; then exit 5; fi

wget http://repo.starwind.com/keys/repo_public.key
if [ "$?" -ne 0 ]; then exit 5; fi

apt-key add repo_public.key
if [ "$?" -ne 0 ]; then exit 5; fi


systemctl daemon-reload
if [ "$?" -ne 0 ]; then exit 5; fi

if ! [ -f /etc/apt/sources.list.d/starwind-san-and-nas.list ]; 
then
	print_and_log "${GREEN}Create apt.list file.${NORMAL}"
	touch /etc/apt/sources.list.d/starwind-san-and-nas.list
	cat <<EOF > /etc/apt/sources.list.d/starwind-san-and-nas.list
$san_repo
deb [arch=amd64 trusted=yes] https://nginx.org/packages/ubuntu/ focal nginx
EOF
else
	print_and_log "${GREEN}apt.list file exist.${NORMAL}"
fi

rm -f /etc/apt/sources.list.d/aerospike.list
if [ "$?" -ne 0 ]; then exit 5; fi

rm -f /etc/apt/sources.list.d/microsoft-prod.list
if [ "$?" -ne 0 ]; then exit 5; fi

rm -f /etc/apt/sources.list.d/vsa.list
if [ "$?" -ne 0 ]; then exit 5; fi

if ! [ -d /etc/systemd/system/getty@tty1.service.d/ ]; 
then
	print_and_log "${GREEN}Create getty@tty1.service.d folder.${NORMAL}"
	mkdir -p /etc/systemd/system/getty@tty1.service.d
	touch /etc/systemd/system/getty@tty1.service.d/override.conf
	cat <<EOF > /etc/systemd/system/getty@tty1.service.d/override.conf
[Unit]
Description=Switch to TTY2

[Service]
ExecStart=
ExecStart=-/usr/bin/chvt 2
Restart=on-failure
RemainAfterExit=yes
StandardInput=tty
StandardOutput=tty

EOF
else
	print_and_log "${GREEN}Folder getty@tty1.service.d exist.${NORMAL}"
fi

if ! [ -d /etc/systemd/system/getty@tty2.service.d/ ]; 
then
	print_and_log "${GREEN}Create getty@tty2.service.d folder.${NORMAL}"
	mkdir -p /etc/systemd/system/getty@tty2.service.d
	touch /etc/systemd/system/getty@tty2.service.d/override.conf
	cat <<EOF > /etc/systemd/system/getty@tty2.service.d/override.conf
[Unit]
Description=Text User Interface of StarWind SAN & NAS on %I

[Service]
ExecStart=
ExecStart=-/usr/bin/python3 /opt/starwind/starwind-san-and-nas-tui/app/welcome.py <> /dev/tty2 >&0 2>& /opt/starwind/starwind-san-and-nas-tui/app/getty-tty2.service.log
Restart=always
RuntimeMaxSec=3600
RemainAfterExit=yes
StandardInput=tty
StandardOutput=tty

EOF
else
	print_and_log "${GREEN}Folder getty@tty1.service.d exist.${NORMAL}"
fi

python3 -m pip install python-pam==1.8.4
if [ "$?" -ne 0 ]; then exit 5; fi

python3 -m pip install jinja2 pathlib
if [ "$?" -ne 0 ]; then exit 5; fi

if ! [ -f /etc/systemd/system/get_network.service ]; 
then
	print_and_log "${GREEN}Create get_network.service.${NORMAL}"
	touch /etc/systemd/system/get_network.service
	cat <<EOF > /etc/systemd/system/get_network.service
[Unit]
Description=Get network information
After=network-online.target network.target

[Service]
ExecStart=/usr/bin/python3 /opt/starwind/starwind-san-and-nas-tui/app/get_network.py
Wants=getty@tty2.service

[Install]
WantedBy=multi-user.target

EOF
else
	print_and_log "${GREEN}get_network.service exist.${NORMAL}"
fi

# rm -f /etc/netplan/01-netcfg.yaml
# if [ "$?" -ne 0 ]; then exit 5; fi

if ! [ -f /etc/default/grub.d/grub_override.cfg ]; 
then
	print_and_log "${GREEN}Create grub_override.cfg.${NORMAL}"
	touch /etc/default/grub.d/grub_override.cfg
	cat <<EOF > /etc/default/grub.d/grub_override.cfg
GRUB_CMDLINE_LINUX_DEFAULT="quiet net.ifnames=0 biosdevname=0"

EOF
else
	print_and_log "${GREEN}grub_override.cfg exist.${NORMAL}"
fi

# if ! [ -f /etc/netplan/eth0.yaml ]; 
# then
	# print_and_log "${GREEN}Create netplan eth0.yaml.${NORMAL}"
	# touch /etc/netplan/eth0.yaml
	# cat <<EOF > /etc/netplan/eth0.yaml
# network:
  # version: 2
  # renderer: networkd
  # ethernets:
    # eth0:
      # dhcp4: yes
      # dhcp-identifier: duid

# EOF
# else
	# print_and_log "${GREEN}Netplan eth0.yaml exist.${NORMAL}"
# fi

# if ! [ -f /etc/netplan/eth1.yaml ]; 
# then
	# print_and_log "${GREEN}Create netplan eth1.yaml.${NORMAL}"
	# touch /etc/netplan/eth1.yaml
	# cat <<EOF > /etc/netplan/eth1.yaml
# network:
  # version: 2
  # renderer: networkd
  # ethernets:
    # eth1:
      # dhcp4: yes
      # dhcp-identifier: duid

# EOF
# else
	# print_and_log "${GREEN}Netplan eth1.yaml exist.${NORMAL}"
# fi

update-grub
if [ "$?" -ne 0 ]; then exit 5; fi

#netplan generate
#if [ "$?" -ne 0 ]; then exit 5; fi

#netplan apply
#if [ "$?" -ne 0 ]; then exit 5; fi

mkdir -p /etc/starwind
if [ "$?" -ne 0 ]; then exit 5; fi

rm -f /usr/local/bin/prestarter.sh
if [ "$?" -ne 0 ]; then exit 5; fi

if ! [ -f /usr/local/bin/prestarter.sh ]; 
then
	print_and_log "${GREEN}Create prestarter.sh.${NORMAL}"
	touch /usr/local/bin/prestarter.sh
	cat <<EOF > /usr/local/bin/prestarter.sh
#!/bin/bash

dllfile="/opt/starwind/starwind-san-and-nas-console/VSAManagementConsole.dll"
crtfile="/etc/starwind/https.chained.crt"
ccfile="/opt/starwind/service_summary.txt"

function createVSAFile {
    crtfingerprint=\`openssl x509 -noout -fingerprint -sha1 -inform pem -in \$crtfile  | awk -F "=" '{gsub(":","");print \$2}'\`
    ninterface="eth0"
    #ipadr=\`ifconfig \$ninterface | grep 'inet' | cut -d: -f2 | awk '{print \$2}'\`
    ipadr=\`ip a show \$ninterface | grep inet | cut -d: -f2 | awk '{print \$2}' |cut -d/ -f1\`
    splt=\`echo "====================================================================="\`
    vsabuild=\`strings \$dllfile | egrep '^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+\$'\`
    vsadate=\`stat \$dllfile | grep Modify | awk '{print \$2}'\`
    echo -ne \\
"\$splt
Build: \$vsabuild (\$vsadate)
Web console: https://\$ipadr
SSL certificate fingerprint: \$crtfingerprint
\$splt
" >\$ccfile
}

createVSAFile

EOF
else
	print_and_log "${GREEN}Prestarter exist. Cannot complete${NORMAL}"
	exit 1
fi

chmod 0775 /usr/local/bin/prestarter.sh
if [ "$?" -ne 0 ]; then exit 5; fi

mkdir -p /opt/starwind/
if [ "$?" -ne 0 ]; then exit 5; fi

if ! [ -f /opt/starwind/ip_change.sh ]; 
then
	print_and_log "${GREEN}Create ip_change.sh.${NORMAL}"
	touch /opt/starwind/ip_change.sh
	cat <<EOF > /opt/starwind/ip_change.sh
#!/bin/bash

generate_http_cert 

/usr/local/bin/prestarter.sh

EOF
else
	print_and_log "${GREEN}ip_change.sh exist.${NORMAL}"
fi

chmod 0775 /opt/starwind/ip_change.sh
if [ "$?" -ne 0 ]; then exit 5; fi

ufw delete allow 8643/tcp
if [ "$?" -ne 0 ]; then exit 5; fi

ufw delete allow 5044/tcp
if [ "$?" -ne 0 ]; then exit 5; fi

ufw delete allow 5043/tcp
if [ "$?" -ne 0 ]; then exit 5; fi

print_and_log "${BOLD}Install starwind-san-and-nas.${NORMAL}"
print_and_log "${BOLD}#########################################################################${NORMAL}"

apt update
if [ "$?" -ne 0 ]; then exit 6; fi

apt install -yq starwind-san-and-nas
if [ "$?" -ne 0 ]; then exit 6; fi

apt install -yq starwind-updater virt-what apt-show-versions nvme-cli samba nfs-kernel-server
if [ "$?" -ne 0 ]; then exit 6; fi

print_and_log "${BOLD}Stoping services:${NORMAL}"
print_and_log "${BOLD}#########################################################################${NORMAL}"

stop_service starwind-metrics-provider.service
if [ "$?" -ne 0 ]; then exit 1; fi

stop_service starwind-metrics-store.service
if [ "$?" -ne 0 ]; then exit 1; fi

stop_service starwind-san-and-nas-console.service
if [ "$?" -ne 0 ]; then exit 1; fi

stop_service starwind-vcenter-plugin.service
if [ "$?" -ne 0 ]; then exit 1; fi

stop_service starwind-virtual-san.service
if [ "$?" -ne 0 ]; then exit 1; fi


print_and_log "${BOLD}Checking services is active:${NORMAL}"
print_and_log "${BOLD}#########################################################################${NORMAL}"


check_service starwind-metrics-provider.service
if [ "$?" -ne 0 ]; then exit 2; fi

check_service starwind-metrics-store.service
if [ "$?" -ne 0 ]; then exit 2; fi

check_service starwind-san-and-nas-console.service
if [ "$?" -ne 0 ]; then exit 2; fi

check_service starwind-vcenter-plugin.service
if [ "$?" -ne 0 ]; then exit 2; fi

check_service starwind-virtual-san.service
if [ "$?" -ne 0 ]; then exit 2; fi

print_and_log "${BOLD}Restore old configs:${NORMAL}"
print_and_log "${BOLD}#########################################################################${NORMAL}"

function copy_cfg_files {
print_and_log "Copy files to templorary folder"
cp -rf $backup_dir/$1 $2 2> >(tee >(cat >> $log_file))
if [[ $? -ne 0 ]]
then
   print_and_log "${RED}Can not copy files.${NORMAL}"
   return 4
else
   print_and_log "${GREEN}Files copied succesfuly.${NORMAL}"
fi
}

copy_cfg_files "PerformanceDataService/StarStack.db" "/opt/starwind/starwind-metrics-provider"
if [ "$?" -ne 0 ]; then exit 3; fi

copy_cfg_files "StarWindVSA/events" "/opt/starwind/starwind-virtual-san/drive_c/starwind"
if [ "$?" -ne 0 ]; then exit 3; fi

copy_cfg_files "StarWindVSA/NotifyDB" "/opt/starwind/starwind-virtual-san/drive_c/starwind"
if [ "$?" -ne 0 ]; then exit 3; fi

copy_cfg_files "StarWindVSA/PerformanceDB" "/opt/starwind/starwind-virtual-san/drive_c/starwind"
if [ "$?" -ne 0 ]; then exit 3; fi

copy_cfg_files "StarWindVSA/StarWind.cfg" "/opt/starwind/starwind-virtual-san/drive_c/starwind"
if [ "$?" -ne 0 ]; then exit 3; fi

copy_cfg_files "StarWindVSA/system.reg" "/opt/starwind/starwind-virtual-san/"
if [ "$?" -ne 0 ]; then exit 3; fi

copy_cfg_files "TelegrafMetricsStore/StarStack.db" "/opt/starwind/starwind-metrics-store"
if [ "$?" -ne 0 ]; then exit 3; fi

copy_cfg_files "StarWindvCenterPlugin/StarStack.db" "/opt/starwind/starwind-vcenter-plugin"
if [ "$?" -ne 0 ]; then exit 3; fi

copy_cfg_files "VSAManagementConsole/VSAManagementConsole.db" "/opt/starwind/starwind-san-and-nas-console"
if [ "$?" -ne 0 ]; then exit 3; fi

copy_cfg_files "VSAManagementConsole/ccsdlocal" "/opt/starwind/starwind-san-and-nas-console"
if [ "$?" -ne 0 ]; then exit 3; fi

mv /opt/component_versions.txt /opt/starwind/


print_and_log "${BOLD}Ensure that logrotate for Starwind services exist.${NORMAL}"
print_and_log "${BOLD}#########################################################################${NORMAL}"


rm -f /etc/logrotate.d/VSAManagementConsole

rm -f /lib/systemd/system/logrotate.timer

function logrotate {
if ! [ -f /etc/logrotate.d/$1 ];
then
        print_and_log "${GREEN}Create $1 file.${NORMAL}"
        touch /etc/logrotate.d/$1
        cat <<EOF > /etc/logrotate.d/$1
/var/log/starwind/$1/*.log {
    size 50M
    maxage 180
    missingok
    notifempty
    copytruncate
    dateext
    compress
    rotate 20
    dateformat -%Y%m%d-%s
 }

EOF
else
        print_and_log "${GREEN}$1 file exist.${NORMAL}"
fi

}


logrotate starwind-vcenter-plugin
if [ "$?" -ne 0 ]; then exit 8; fi
logrotate starwind-metrics-provider
if [ "$?" -ne 0 ]; then exit 8; fi
logrotate starwind-metrics-store
if [ "$?" -ne 0 ]; then exit 8; fi
logrotate starwind-san-and-nas-console
if [ "$?" -ne 0 ]; then exit 8; fi
logrotate starwind-license-manager
if [ "$?" -ne 0 ]; then exit 8; fi
logrotate starwind-updater
if [ "$?" -ne 0 ]; then exit 8; fi

if ! [ -f /lib/systemd/system/logrotate.timer ];
then
        echo -e "${GREEN}Create apt.list file.${NORMAL}"
        touch /lib/systemd/system/logrotate.timer
        cat <<EOF > /lib/systemd/system/logrotate.timer
[Unit]
Description=Daily rotation of log files
Documentation=man:logrotate(8) man:logrotate.conf(5)

[Timer]
OnBootSec=60m
OnUnitActiveSec=60m

[Install]
WantedBy=timers.target

EOF
else
        echo -e "${GREEN}timer file exist.${NORMAL}"
fi


print_and_log "${BOLD}CLEANUP.${NORMAL}"
print_and_log "${BOLD}#########################################################################${NORMAL}"

cat /dev/null > /etc/samba/smb.conf
if [ "$?" -ne 0 ]; then exit 7; fi

rm -rf PERCCLI_7.1910.00_A12_Linux PERCCLI_7.1910.00_A12_Linux.tar.gz
if [ "$?" -ne 0 ]; then exit 7; fi

rm -f repo_public.key
if [ "$?" -ne 0 ]; then exit 7; fi

rm -f nginx_signing.key
if [ "$?" -ne 0 ]; then exit 7; fi

systemctl enable getty@tty2.service
if [ "$?" -ne 0 ]; then exit 7; fi

systemctl enable get_network.service
if [ "$?" -ne 0 ]; then exit 7; fi

sudo chmod 755 /opt/starwind/starwind-metrics-store/ /opt/starwind/starwind-metrics-provider/
if [ "$?" -ne 0 ]; then exit 7; fi

echo "@reboot         root    generate_http_cert && /usr/local/bin/prestarter.sh" >> /etc/crontab
if [ "$?" -ne 0 ]; then exit 7; fi

sed -i 's/'$interface1'/eth0/g' /etc/aerospike/aerospike.conf
if [ "$?" -ne 0 ]; then exit 7; fi

sed -i 's/'$interface1'/eth0/g' /etc/NetworkManager/system-connections/Wired\ connection\ 1.nmconnection
if [ "$?" -ne 0 ]; then exit 7; fi

sed -i 's/'$interface2'/eth1/g' /etc/NetworkManager/system-connections/Wired\ connection\ 2.nmconnection
if [ "$?" -ne 0 ]; then exit 7; fi

if ! [ -f /etc/nginx/sites-available/proxy-updater.conf ]; 
then
	print_and_log "${GREEN}Create proxy-updater.conf.${NORMAL}"
	touch /etc/nginx/sites-available/proxy-updater.conf
	cat <<EOF > /etc/nginx/sites-available/proxy-updater.conf
server {
    listen 80;
    server_name _;
    return 301 https://\$host\$request_uri;
}

server {
    ### Product proxy
    listen 443 ssl;
    include /etc/nginx/starwind-certificates.conf;
    #ssl_protocols TLSv1.2 TLSv1.3;
    client_max_body_size 0;
    proxy_request_buffering off;
    ssl_ciphers ECDH+AESGCM:ECDH+AES256:ECDH+AES128:DH+3DES:!ADH:!AECDH:!MD5;
    ssl_prefer_server_ciphers off;

    include /etc/nginx/proxy_params;

    underscores_in_headers on;
    location / {
        proxy_ssl_verify off;
        proxy_http_version 1.1;
        proxy_read_timeout 900;
        proxy_set_header Connection \$http_connection;
        proxy_set_header Upgrade \$http_upgrade;
        proxy_pass_request_headers on;
        proxy_pass http://127.0.0.1:8100;
        proxy_set_header Host \$host;
        proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;
        proxy_set_header X-Real-IP \$remote_addr;
    }

    location /updater {
        ### Using additional server for updater webui
        add_header Strict-Transport-Security "max-age=2592000" always;
        add_header X-Frame-Options DENY always;
        add_header Referrer-Policy no-referrer;
        add_header X-Content-Type-Options nosniff;
        add_header Content-Security-Policy "default-src 'none';script-src 'self';style-src 'self' https://fonts.googleapis.com/css 'unsafe-inline';connect-src 'self';manifest-src 'self';font-src 'self' https://fonts.gstatic.com/s/;img-src 'self';" always;
        rewrite ^/updater/(.*)\$ /\$1 break;
        proxy_pass http://127.0.0.1:9000;
   }

   include /etc/nginx/sites-available/*proxy_pass.conf;
}

EOF
else
	print_and_log "${GREEN}File proxy-updater.conf exist.${NORMAL}"
fi

if ! [ -f /etc/nginx/proxy_params ]; 
then
	print_and_log "${GREEN}Create proxy_params.${NORMAL}"
	touch /etc/nginx/proxy_params
	cat <<EOF > /etc/nginx/proxy_params
proxy_set_header Host \$http_host;
proxy_set_header X-Real-IP \$remote_addr;
proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto \$scheme;

EOF
else
	print_and_log "${GREEN}File proxy_params exist.${NORMAL}"
	#exit 7
fi

if ! [ -f /etc/nginx/starwind-certificates.conf ]; 
then
	print_and_log "${GREEN}Create starwind-certificates.conf.${NORMAL}"
	touch /etc/nginx/starwind-certificates.conf
	cat <<EOF > /etc/nginx/starwind-certificates.conf
ssl_certificate     /etc/starwind/https.chained.crt;
ssl_certificate_key /etc/starwind/ca.key;

EOF
else
	print_and_log "${GREEN}File starwind-certificates.conf exist.${NORMAL}"
	#exit 1
fi

# mkdir -p /etc/nginx/sites-enabled
# if [ "$?" -ne 0 ]; then exit 7; fi

# ln -s /etc/nginx/sites-available/proxy-updater.conf /etc/nginx/sites-enabled/proxy-updater.conf
# if [ "$?" -ne 0 ]; then exit 7; fi

# ln -s /etc/nginx/sites-available/proxy-updater.conf /etc/nginx/conf.d/proxy-updater.conf
# if [ "$?" -ne 0 ]; then exit 7; fi

# rm -f /etc/nginx/conf.d/default.conf
# if [ "$?" -ne 0 ]; then exit 7; fi

print_and_log "${GREEN}Create starwind-updatemanager/appsettings.json.${NORMAL}"
touch /opt/starwind/starwind-updatemanager/appsettings.json
cat <<EOF > /opt/starwind/starwind-updatemanager/appsettings.json
{
  "productId": "1389955e-fafa-41cb-b80c-a08003f47430",
  "configId": "b402a0c7-4812-41c4-81ee-151626528c48",
  "configVersion" : "1.0",

  "SiteSettings": {
    "NetworkSettings": {
      "API_port": 9000,
      "API_SSL_port": 9001,
      "UseHttps": false,
      "RedirectToHTTPS": false,
      "UseLocalhost": true
    }
  },
  "TimeoutsInSec": {
    "bash" : 300
  },
  "Log": {
    "LogLevel": "Info",
    "FileName": "/var/log/starwind/starwind-updater/starwind_updater.log",
    "DisableWebHostLogging": true,
    "DisableConsoleOutput": false
  },
  "PlatformAuthenticatorConfig": {
    "CertificatesDirectoryPath": "/etc/starwind-updater"
  }
}

EOF

print_and_log "${GREEN}Create starwind-updatemanager - b402a0c7-4812-41c4-81ee-151626528c48.json.${NORMAL}"
mkdir -p /opt/starwind/starwind-updatemanager/1389955e-fafa-41cb-b80c-a08003f47430
touch /opt/starwind/starwind-updatemanager/1389955e-fafa-41cb-b80c-a08003f47430/b402a0c7-4812-41c4-81ee-151626528c48.json
cat <<EOF > /opt/starwind/starwind-updatemanager/1389955e-fafa-41cb-b80c-a08003f47430/b402a0c7-4812-41c4-81ee-151626528c48.json
{
  "productId": "1389955e-fafa-41cb-b80c-a08003f47430",
  "configId": "b402a0c7-4812-41c4-81ee-151626528c48",
  "origins": [
    {
      "id": "d3b23ea4-753b-4099-805d-82973681bf73",
      "name": "VSA",
      "repositories": [
        "deb [arch=amd64 trusted=yes] http://repo.starwind.com/san-and-nas/ focal main"
      ],
      "selectedPackages": [
        "starwind-san-and-nas"
      ],
      "postUpdateScript": "/usr/local/bin/prestarter.sh"
    }
  ]
}

EOF


ufw allow 22
if [ "$?" -ne 0 ]; then exit 7; fi
ufw allow 80
if [ "$?" -ne 0 ]; then exit 7; fi
ufw allow 443
if [ "$?" -ne 0 ]; then exit 7; fi
ufw allow 3261
if [ "$?" -ne 0 ]; then exit 7; fi
ufw allow 3260
if [ "$?" -ne 0 ]; then exit 7; fi

print_and_log "${BOLD}REBOOT${NORMAL}"
print_and_log "${BOLD}#########################################################################${NORMAL}"

sleep 10

reboot

         ;;
        n|N) exit 1
        ;;
esac

