#!/bin/sh

##########################################################################
#   Title:
#       Optional, defaults to the name of the script sans extention
#
#   Section:
#       8
#
#   Synopsis:
#       
#   Description:
#       
#   Arguments:
#       
#   Returns:
#
#   Examples:
#
#   Files:
#
#   Environment:
#
#   See also:
#       
#   History:
#   Date        Name        Modification
#   2024-09-23  Jason Bacon Add man page template and usage
##########################################################################

usage()
{
    printf "Usage: $0\n"
    exit 1
}


##########################################################################
#   Main
##########################################################################

if [ `id -un` != 'root' ]; then
    printf "$0 must be run by root.\n"
    exit 1
fi

if [ $# != 0 ]; then
    usage
fi

case `auto-ostype` in
FreeBSD)
    printf "Clean package cache? [y]/n "
    read clean
    if [ 0$clean != 0n ]; then
	pkg clean -a
    fi
    
    printf "Clean ports tree? [y]/n "
    read clean
    if [ 0$clean != 0n ]; then
	auto-clean-ports
    fi
    
    mount_points=`awk '$3 == "ufs" { print $2 }' /etc/fstab`
    set +e
    for dir in $mount_points; do
	printf "Zero free blocks on $dir? y/[n] "
	read zero
	if [ 0$zero = 0y ]; then
	    fs=$(df -T $dir | fgrep -v Filesystem | awk '{ print $2 }')
	    echo $fs
	    if [ $fs = zfs ]; then
		printf "Temporarily disabling dedup on $dir...\n"
		dedup=$(zfs get -H -o value dedup $dir)
		zfs set dedup=off $dir
	    fi
	    dd if=/dev/zero of=$dir/zero-temp bs=1m
	    rm -f $dir/zero-temp
	    if [ $fs = zfs ]; then
		zfs set dedup=$dedup $dir
	    fi
	fi
    done
    ;;

NetBSD)
    printf "Clean pkgsrc cache and tree? [y]/n "
    read clean
    if [ 0$clean != 0n ]; then
	auto-clean-pkgsrc
    fi
    
    mount_points=`awk '$3 == "ffs" { print $2 }' /etc/fstab`
    set +e
    for dir in $mount_points; do
	printf "Zero free blocks on $dir? y/[n] "
	read zero
	if [ 0$zero = 0y ]; then
	    cd $dir
	    dd if=/dev/zero of=zero-temp bs=1m
	    rm zero-temp
	fi
    done
    ;;

RHEL)
    printf "Clean package cache? [y]/n "
    read clean
    if [ 0$clean != 0n ]; then
	yum clean all
    fi
    
    mount_points=`awk '$3 ~ "ext" || $3 ~ "xfs" { print $2 }' /etc/fstab`
    set +e
    for dir in $mount_points; do
	printf "Zero free blocks on $dir? y/[n] "
	read zero
	if [ 0$zero = 0y ]; then
	    cd $dir
	    dd if=/dev/zero of=zero-temp bs=1M
	    rm zero-temp
	fi
    done
    ;;

*)
    auto-unsupported-os $0
    exit 1
    ;;

esac
