#!/bin/bash

## Disable console auto-login
sed -i '/ExecStart=-\/sbin\/agetty --autologin root/d' /lib/systemd/system/serial-getty@.service
sed -i '/^#ExecStart=-\/sbin\/agetty -o/s/^#//' /lib/systemd/system/serial-getty@.service

## Enable i2c7 interface
sed -i 's/intfc:i2c7=off/intfc:i2c7=on/g' /boot/hw_intfc.conf

## Modify eth0
if [[ ! -f /etc/NetworkManager/dispatcher.d/99-ethtool-settings.sh ]];then
echo -e '#!/bin/sh\nethtool --offload eth0 gso on sg on gro off rx off tx off' > /etc/NetworkManager/dispatcher.d/99-ethtool-settings.sh
chmod +x /etc/NetworkManager/dispatcher.d/99-ethtool-settings.sh
fi

## Set date if no internet connection
curl -sSL --connect-timeout 3 https://check-live.dmz.ator.dev/api/ip

if [[ $? -eq 0 ]];then
    echo "curl OK"
else
    date -s '2024-10-10 00:13:37'
fi

sleep 1

if [[ $(dpkg -l anon | grep anon | awk '{print $1}') == 'iHR' ]];then
    dpkg --configure -a
fi

## Cleanup
rm -v /home/relayup/dev/html-normal/default.cfg
rm -v /home/relayup/dev/html-normal/temp_*
rm -vrf /home/relayup/dev/html-normal/static
rm -vrf /home/relayup/dev/html-wizard/static
rm -v /home/relayup/dev/00_logs.log
find /home/ -type f -name ".DS_Store" -delete
find /home/ -type f -name "._*" -delete

## Add update and adjust files
cp -r /home/update/* /
chown relayup:relayup /home/relayup/dev/Shield
chmod 774 /home/relayup/dev/Shield
chown relayup:relayup /home/relayup/dev/vpn_install.cfg
chmod 644 /home/relayup/dev/vpn_install.cfg
chmod 666 /home/relayup/dev/vpn_config.cfg
chown relayup:relayup /home/relayup/dev/html-* -R
chmod 777 /home/relayup/dev/html-*
mkdir /home/relayup/dev/sysupdate
chown relayup:relayup /home/relayup/dev/sysupdate
chmod 777 /home/relayup/dev/sysupdate

if [[ $(grep -cw "07_Set=relayup" /home/relayup/dev/00_saved.cfg) -eq 1 ]];then
SHIELD_SERIAL=$(cat /proc/cpuinfo | grep Serial | awk '{print $3}')
sed -i '/07_Set=relayup/s/$/'"_${SHIELD_SERIAL: -6}"'/' /home/relayup/dev/00_saved.cfg
fi

sed -i '/99_Set/d' /home/relayup/dev/00_saved.cfg
sed -i 's/12_Set=.*/12_Set=https:\/\/check.en.anyone.tech\/api\/ip/g' /home/relayup/dev/00_saved.cfg
sed -i 's/21_Set=.*/21_Set=https:\/\/api.ec.anyone.tech\/hardware/g' /home/relayup/dev/00_saved.cfg
sed -i 's/08_Set=ianon.io/08_Set=anyone.io/g' /home/relayup/dev/00_saved.cfg
sed -i 's/RelayBandwidth/Bandwidth/g' /home/update/home/relayup/dev/vpn_config.cfg
sed -i 's/bash \/home\/update\/dependencies.sh/\/home\/relayup\/dev\/Shield -R/g' /etc/cron.d/onboot

## Enable auto-start for anon
if [[ $(systemctl is-enabled anon | grep -wc "disabled" ) -eq 1 ]];then
    systemctl enable anon
fi
   
##
rm -r /home/update
sudo reboot