#!/bin/sh -e

##########################################################################
#   Title:
#       Optional, defaults to the name of the script sans extention
#
#   Section:
#       8
#
#   Synopsis:
#       
#   Description:
#       Clean FreeBSD or MacPorts work directories
#       
#   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 [ $# != 0 ]; then
    usage
fi

: ${PORTSDIR:=/usr/ports}

case $(auto-ostype) in
FreeBSD)
    before=$(df -m $PORTSDIR | awk '$1 != "Filesystem" { print $4 }')
    printf "Initial free space: %d\n" $before
    cd $PORTSDIR
    rm -rf distfiles/* > /dev/null 2>&1
    for dir in $(ls -d */*/work*); do
	# Make sure it still exists - may have been wiped by a recursive clean
	if [ -e $dir ]; then
	    echo "Cleaning $dir..."
	    cd $dir/..
	    make clean
	    cd $PORTSDIR
	fi
    done
    after=$(df -m $PORTSDIR | awk '$1 != "Filesystem" { print $4 }')
    printf "Initial free space: %d\n" $before
    printf "Final free space: %d\n" $after
    diff=$(($after - $before))
    printf "%d megabytes freed.\n" $diff
    ;;

Darwin)
    port clean --all installed
    ;;

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

esac

