#!/usr/bin/env bash
set -euo pipefail

if [[ ${EUID:-$(id -u)} -ne 0 ]]; then
  exec sudo -E bash "$0" "$@"
fi

log() { printf "[%s] %s\n" "$(date +%H:%M:%S)" "$*"; }
report_space() {
  log "$1"
  df -h / /home 2>/dev/null || df -h /
}

report_space "Before cleanup"

log "Set snap revision retention to 2"
snap set system refresh.retain=1 || snap set system refresh.retain=2

log "Remove disabled snap revisions"
snap list --all | awk "/disabled/{print \$1, \$3}" | while read -r name rev; do
  [[ -n ${name:-} && -n ${rev:-} ]] || continue
  snap remove "$name" --revision="$rev" || true
 done

log "Hold snap refreshes indefinitely"
snap refresh --hold=forever || true

log "Disable apt automatic updates"
install -d /etc/apt/apt.conf.d
cat >/etc/apt/apt.conf.d/20auto-upgrades <<EOC
APT::Periodic::Update-Package-Lists "0";
APT::Periodic::Unattended-Upgrade "0";
EOC
systemctl disable --now unattended-upgrades.service apt-daily.timer apt-daily-upgrade.timer update-notifier-download.timer update-notifier-motd.timer 2>/dev/null || true
systemctl mask unattended-upgrades.service apt-daily.timer apt-daily-upgrade.timer update-notifier-download.timer update-notifier-motd.timer 2>/dev/null || true

log "Recreate swap as 1G"
if swapon --noheadings --raw --show=NAME | grep -qx "/swap.img"; then
  swapoff /swap.img
fi
rm -f /swap.img
fallocate -l 1G /swap.img 2>/dev/null || dd if=/dev/zero of=/swap.img bs=1M count=1024 status=none
chmod 600 /swap.img
mkswap /swap.img >/dev/null
grep -qE ^/swap.img[[:space:]]+none[[:space:]]+swap[[:space:]]+sw[[:space:]]+0[[:space:]]+0 /etc/fstab || echo /swap.img none swap sw 0 0 >> /etc/fstab
swapon /swap.img

log "Limit journal size to 1G"
install -d /etc/systemd/journald.conf.d
cat >/etc/systemd/journald.conf.d/99-storage-optimizer.conf <<EOC
[Journal]
SystemMaxUse=1G
RuntimeMaxUse=1G
EOC
systemctl restart systemd-journald
journalctl --vacuum-size=1G >/dev/null || true

log "Done"
report_space "After cleanup"
