#!/bin/sh
set -eu

usage() {
	cat <<-'EOF'
	Usage:
	  gc
	  gc -h
EOF
}

help() {
	cat <<-'EOF'

	Options:
	  -h, --help    show this message
EOF
}

for flag in "$@"; do
	case "$flag" in
		--)
			break
			;;
		--help)
			usage
			help
			exit
			;;
		*)
			;;
	esac
done

while getopts 'h' flag; do
	case "$flag" in
		h)
			usage
			help
			exit
			;;
		*)
			usage >&2
			exit 2
			;;
	esac
done
shift $((OPTIND - 1))

set -x
before="$(df -h .)"

PROFILES='
per-user/root/channels
per-user/andreh/profile
per-user/andreh/channels
system
'

for p in $PROFILES; do
  doas nix-env --delete-generations old -p "/nix/var/nix/profiles/$p"
done
nix-env --delete-generations old
nix-store --gc
nix-collect-garbage -d

guix gc -d

find ~/ -name 'nohup.out' -exec rm {} \;
rm -rf ~/.local/share/Trash/files/*
find /tmp/ -type f -atime +10 -exec rm {} \; ||:

if command -V docker; then
  echo y | docker system prune -a
  docker rmi "$(docker images -a -q)" ||:
  docker rm "$(docker ps -a -f status=exited -q)" ||:
  docker stop "$(docker ps -a -q)" ||:
  docker rm "$(docker ps -a -q)" ||:
  echo y | docker volume prune
  echo y | docker container prune
fi

notmuch search --output=files --exclude=false tag:deleted | xargs -I{} rm "{}"
notmuch new

after="$(df -h .)"

set +x
echo 'Disk space before and after:'
echo "  before: $before"
echo "  after:  $after"
