#!/bin/bash

# The script cleans up a system for cloning preparation.
# Author: Howard Guo <hguo@suse.com>

set -e

err_exit() {
  echo "Sorry! An error occured on line $1, the clean up routine did not complete successfully."
  exit 1
}
trap 'err_exit $LINENO' ERR

[ "$UID" != "0" ] && echo 'Please run this program as root user.' && exit 1

echo 'The script will delete all SSH keys, log data, and more. Type YES and enter to proceed.'
read answer
[ "$answer" != "YES" ] && exit 1

echo 'Wiping active swap devices/files (this may take a while)'
while read swap_name discard; do
  uuid=$(env $(blkid -o export "$swap_name") printenv UUID)
  echo "Turning off swap device/file $swap_name (UUID $uuid)"
  swapoff "$swap_name"
  echo "Zero-overwriting $swap_name..."
  shred -n1 --random-source=/dev/zero "$swap_name"
  mkswap "$swap_name" -U "$uuid"
done < <(tail -n+2 /proc/swaps)

echo 'Removing system registration information and zypper repositories'
> /etc/SUSEConnect
find /etc/zypp \( -iname 'suse*' -o -iname 'scc*' \) -delete

echo 'Removing SSH host keys, user SSH keys, authorized keys, and shell history'
rm -rf /etc/ssh/ssh_host*key* /root/.ssh/* /home/*/.ssh/* /home/*/.*_history &> /dev/null

echo 'Removing all mails and cron-jobs'
rm -rf /var/spool/mail/*
rm -rf /var/spool/cron/{lastrun,tabs}/*

echo 'Removing all temporary files'
rm -rf /tmp/* /tmp/.* /var/tmp/* /var/tmp/.* &> /dev/null || true

echo 'Clearing log files and removing log archives'
find /var/log -type f -exec truncate -s 0 {} \;
find /var/log \( -iname '*.old' -o -iname '*.xz' -o -iname '*.gz' \) -delete

echo 'Clearing HANA firewall script'
rm -rf /etc/hana-firewall.d/generated_hana_firewall_script

echo 'Removing random seeds'
for seed in /var/lib/systemd/random-seed /var/lib/misc/random-seed; do
[ -f "$seed" ] && rm -f "$seed"
done

echo 'Clearing systemd journal'
pushd /etc/systemd
cp journald.conf journald.conf.bak
echo -e '\nSystemMaxUse=1K' >> journald.conf
systemctl restart systemd-journald
mv journald.conf.bak journald.conf
popd

echo 'Removing domain name and set host name from DHCP in network config'
sed -i 's/^NETCONFIG_DNS_STATIC_SEARCHLIST=.*$/NETCONFIG_DNS_STATIC_SEARCHLIST=""/g' /etc/sysconfig/network/config
sed -i 's/^DHCLIENT_SET_HOSTNAME=.*$/DHCLIENT_SET_HOSTNAME="yes"/g' /etc/sysconfig/network/dhcp

echo 'Removing persistent network interfaces'
netudev=/etc/udev/rules.d/70-persistent-net.rules
if [ -f "$netudev" ]; then
  if grep -i 'automatically generated' "$netudev" &> /dev/null; then
    rm "$netudev"
  fi
fi

echo 'Restoring initial system-wide network config'
truncate -s 0 /etc/{hostname,hosts,resolv.conf}
cat << EOF > /etc/hosts
127.0.0.1       localhost
::1             localhost ipv6-localhost ipv6-loopback
fe00::0         ipv6-localnet
ff00::0         ipv6-mcastprefix
ff02::1         ipv6-allnodes
ff02::2         ipv6-allrouters
ff02::3         ipv6-allhosts
EOF

echo 'Enabling YaST Firstboot if necessary'
[ -e /etc/YaST2/firstboot.xml ] && touch /var/lib/YaST2/reconfig_system

echo 'Restoring initial sudoers settings'
cat << EOF > /etc/sudoers
Defaults always_set_home
Defaults env_reset
Defaults env_keep = "LANG LC_ADDRESS LC_CTYPE LC_COLLATE LC_IDENTIFICATION LC_MEASUREMENT LC_MESSAGES LC_MONETARY LC_NAME LC_NUMERIC LC_PAPER LC_TELEPHONE LC_TIME LC_ALL LANGUAGE LINGUAS XDG_SESSION_COOKIE"
Defaults secure_path = "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
Defaults targetpw

ALL ALL=(ALL) ALL
root ALL=(ALL) ALL
EOF

echo 'Would you like to give root user a new password? Type YES to set a new password, otherwise simply press Enter.'
read answer
[ "$answer" == "YES" ] && passwd root

if curl --connect-timeout 3 '169.254.169.254/latest' &> /dev/null; then
  echo 'EC2 specific: allowing ec2-user to run sudo'
  echo 'ec2-user ALL=(ALL) ALL' >> /etc/sudoers
  echo 'Note to EC2 user:'
  echo 'This instance will no longer be accessible after a reboot due to removal of all authorized SSH keys.'
  echo "New SSH key will be installed automatically if you create a new instance from this instance's image."
fi

echo 'Finished. The system is now sparkling clean. Feel free to shut it down and image it.'

