#!/usr/bin/env bash
#Cleans system before cloning

function stop-everything() {
	miner stop
	wd stop
	autofan stop
	agent-screen stop
	systemctl stop hivex
}

stop-everything


timedatectl set-timezone UTC


hostname=worker
if ! grep -q "127.0.0.1 $hostname" "/etc/hosts"; then
	printf "\n127.0.0.1 $hostname\n" >> /etc/hosts
fi
hostnamectl set-hostname "$hostname"


/hive/bin/cache-hive-ip resetonly


find /hive -type f -name "*.log" -exec rm -f {} \;
find /hive -type f -name "*.~" -exec rm -f {} \;

[[ -d /hive/ccminer ]] && find /hive/ccminer -type f -name "ccminer_*" -exec rm -f {} \;
[[ -d /hive/custom ]]  && find /hive/custom/ -maxdepth 1 -mindepth 1 -type d -exec rm -rf {} \;
rm /hive/ethminer/progpow/kernel*

mount --bind / /mnt && rm -rf /mnt/var/log/* && umount /mnt
rm -r /var/log/*
#rm /var/log/*.1; rm /var/log/*.2; rm /var/log/*.gz; echo "" > /var/log/kern.log; echo "" > /var/log/syslog
#rm /var/log/*.log
#rm /var/log/apt/*
#rm /var/log/hive*
#rm /var/log/amd-oc.log
mkdir -p /var/log/journal


rm -r /hive-config/*
if [[ -d /etc/hive-config.stub ]]; then
	cp -r /etc/hive-config.stub/* /hive-config/
else
	cp -r /hive/etc/hive-config.stub/* /hive-config/
fi

echo "" > /root/.bash_history
echo "" > /home/user/.bash_history
rm -rf /var/tmp/*
echo "" > /home/user/.ssh/authorized_keys
echo "" > /home/user/.local/share/mc/history
rm /home/user/.local/share/mc/mcedit/mcedit.clip
rm -rf /home/user/.local/share/xorg
rm -rf /home/user/.openclcache
rm -rf /home/user/.nv
rm -rf /home/root/.openclcache
rm -rf /home/root/.nv

systemctl stop wpa_supplicant@wlan0
systemctl disable wpa_supplicant@wlan0
rm /etc/wpa_supplicant/wpa_supplicant.conf

chown -R user:user /hive
chown -R root:root /hive/etc/logrotate.d/*


#no AMD in updates
rm /etc/apt/sources.list.d/amdgpu-pro.list
rm /etc/apt/sources.list.d/amdgpu-pro-local.list
#old DKMS images, they are big!
rm /boot/*.old-dkms
#we don't need i386
rm -rf /opt/amdgpu-pro/lib/i386-linux-gnu

#to replace configs and etc...
selfupgrade
apt install --reinstall hive
stop-everything
hpkg remove miners noinstall
#hpkg install miners phoenixminer #preinstall
#update-usbids
apt clean
apt purge


echo "> Filling /hive-config"
zerofill /hive-config
echo "> Filling /"
zerofill /
echo "Done"
