#!/bin/bash

# search and destroy garbage files in root
find / -type f -iname "thumbs.db" -exec rm {} \; 2> /dev/null &
find / -type f -iname ".ds_store" -exec rm {} \; 2> /dev/null &
find / -type f -name '._*' -exec rm -rf {} \; 2> /dev/null &

# functions for asynchronous operations
cleanup_ext4() {
	fstrim "$1"
	e4defrag "$1"
}

cleanup_btrfs() {
	fstrim "$1"

	btrfs balance start -dusage=1 "$1"
	btrfs balance start -musage=1 "$1"
	btrfs balance start -dusage=5 "$1"
	btrfs balance start -musage=5 "$1"
	btrfs balance start -dusage=10 "$1"
	btrfs balance start -musage=10 "$1"
	btrfs balance start -dusage=25 "$1"
	btrfs balance start -musage=25 "$1"
	btrfs balance start -dusage=50 "$1"
	btrfs balance start -musage=50 "$1"

	btrfs scrub start -qdB "$1"
}

# defragment and fstrim ext4 weekly
for filesystem in $(mount -t ext4 | awk '{print $3}'); do
	cleanup_ext4 "$filesystem" &
done

# defragment and rebalance btrfs weekly
for filesystem in $(mount -t btrfs | awk '{print $3}'); do
	cleanup_btrfs "$filesystem" &
done

# wait for jobs to complete
for j in $(jobs -p); do
	wait $j
done
