#!/bin/sh -e

##########################################################################
#   Script description:
#       
#   Arguments:
#       
#   Returns:
#       
#   History:
#   Date        Name        Modification
#   2015-05-13  root        Begin
##########################################################################

usage()
{
    printf "Usage: $0 [pkgsrc-dir]\n"
    exit 1
}


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

case $# in
0)
    pkgsrc=`auto-pkgsrc-dir`
    ;;
1)
    pkgsrc="$1"
    ;;
*)
    usage
    ;;
esac

# Only if the CURRENTLY ACTIVE tree has pkgin installed
# OpenIndiana sh terminates script if which pkgin fails
if [ -e $(auto-pkgsrc-prefix)/bin/pkgin ]; then
    printf "Cleaning pkg cache...\n"
    # May be two pkgsrc trees in PATH, e.g. NetBSD non-priv and /usr/pkg
    pkgin clean || true
else
    printf "No $(auto-pkgsrc-prefix)/bin/pkgin.  Skipping pkgin clean...\n"
fi

cd "$pkgsrc"

printf "Cleaning $pkgsrc...\n"
if [ $(uname) = Linux ]; then
    df_flags=-Pm    # Is this appropriate for all Linux distros?
else
    df_flags=-m
fi

before=`df $df_flags . | awk '$1 != "Filesystem" { print $4 }'`

make=$(auto-pkgsrc-make)
for dir in */*/work; do
    if [ -e $dir ]; then
	(cd $dir/.. && $make clean)
	# rm -rf $dir   # Fails due to permissions for pkglint
    fi
done

printf "Remove distfiles? y/[n] "
read dist
if [ 0$dist = 0y ]; then
    rm -rf distfiles/*
fi

after=`df $df_flags . | 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
