#!/bin/bash
# pruneXpkgs.sh
# created and copyrighted: 19apr11
#
# author: Evsiz (evsiz@this-voice.org)
# The author releases this file under the GNU GPL
# license. See GNU's COPYING file for specifics.

version () {
 VERSION='Version 19apr11'
 echo "
$VERSION
"
}

help () {
cat << END

 USAGE: pruneXpkgs.sh [option]

 -h|-?|--help ( shows this help info you are reading right now )
 -v|--version ( show which version of this script you have )
 no option    ( displays man page/file list, option to remove pkg )

END
}


is_root () {
    if [ "$(id -u)" != '0' ]; then
        echo "Please su to root or use sudo to run this script."
        exit 1
    fi
}


pruneXpkgs () {
    # get all free packages beginning with an "x"
    PKGS=`ls freepkgs.* 2>/dev/null | head -n 1`
    if [ -z "$PKGS" ]; then
        echo "
pruneXpkgs.sh: no freepkgs log found
You must first run SlackBash's freepkgs.awk.
"
        exit 1
    fi
    
    PKGS=`grep packages/x $PKGS`
    num=0
    for pkg in $PKGS; do
        num=$(($num+1))
    done
    clear
    
    echo -n "
pruneXpkgs.sh found "$num" free packages.

You will be shown the man page or the Slack package list of each package.
Then you will have to option to remove the package or leave it installed.  

Enter 'yes' to continue, anything else to quit => "

    read reply
    if [ "$reply" != "yes" ]; then
        exit
    fi

    # roll through the free packages    
    for pkg in $PKGS; do

	# in case we use the same log twice
	if [ ! -f $pkg ]; then continue; fi

        # get package name
        pname=`echo $pkg | awk '{ \
            split($0, tmp, "/"); \
            name=tmp[5]; \
            count=split(name, tmp, "-"); \
            count = count - 3; \
            pname = tmp[1]; \
            if ( count != 1 ) \
                for (i = 2; i <= count; i++) \
                    pname = pname "-" tmp[i]; \
            fi; \
            print pname; \
        }'`

        # display man page or Slack package file
        man $pname 2>/dev/null || less $pkg

        # option to remove package
        clear

        echo -n "
Current package: "$pkg"
Enter 'yes' to remove, <enter> to continue, Ctl-C to quit

Remove package "$pname"? => "

        read reply
        if [ "$reply" == "yes" ]; then
            removepkg $pname
        fi
    done
}

# script entry point:
LANG=C
export LANG
LC_ALL=C
export LC_ALL

case "$1" in

 --version|-v) version && exit 0 ;;

 --help|-h|-\?) help && exit 0 ;;

 *)
    is_root
    pruneXpkgs
 ;;

esac
