#!/bin/sh

THIS="/usr/bin/javacpmgr"
ACTION=""
JAVACFGDIR="/etc/sysconfig/java"
JAVACONF="/etc/sysconfig/java.conf"
LIBDIR="/usr/lib/java-env"

if [ -z "$CONFIG_DIR" ]; then
    CFGDIR="$HOME/.java"
    HOMECONF="$CONFDIR/java.conf"
else
    CFGDIR="$HOME/etc/java"
    HOMECONF="$CONFDIR/java.conf"
fi

UID=`id -u`
USAGE="false"

no_other_action() {
    if [ ! -z "$ACTION" ]; then 
    	echo "Do not use $1 with other action!"
    	exit 1
    fi
}

other_option() {
    if [ "$1" -eq 0 ]; then 
    	echo "$2 require another option!"
    	exit 1
    fi
}

root_req() {
    if [ "$UID" -ne "0" ]; then
	echo "You must be root to use $1"
	exit 1
    fi
}

# get command line options
while test $# -gt 0; do
    case "$1" in
	--getlocalcp)
	    no_other_action "$1"; shift
	    ACTION="GETLOCALCP"
	    ;;
	--findjars)
	    no_other_action "$1"; shift
	    other_option "$#" "--findjars"; JARDIR="$1"; shift
	    [ "$#" -ne 0 ] && FORMAT="$1" && shift
    	    ACTION="FINDJARS"
	    ;;
	-h | --help) 
	    USAGE="true"; shift;;
	*)
	    USAGE="true"; shift;;
    esac    
done

[ -z "$ACTION" ] && USAGE="true"
if [ "$USAGE" == "true" ]; then
    cat "$LIBDIR/javacpmgr.usage.txt"
    exit 0
fi

case "$ACTION" in
    FINDJARS)
	if [ ! -d "$JARDIR" ]; then
	    echo "$JARDIR directory not found!"
	    exit 1
	fi

	[ -z "$FORMAT" ] && FORMAT="# /%P\n"

	find $JARDIR -type f -name "*.jar" -printf "$FORMAT"	
	;;
    GETLOCALCP)
	[ ! -d "$CFGDIR" ] && CFGDIR="$JAVACFGDIR"
	[ ! -f "$HOMECONF" ] && HOMECONF="$JAVACONF"
	CP=""
	for FILE in `ls $CFGDIR/cp.* 2> /dev/null`
	do
	    TMP=`cat $FILE | grep -v "#" | awk '{ if (NR == 1) { printf "%s", $1 } else { printf ":%s", $1 } }'`
	    if [ ! -z "$TMP" ]; then
		[ ! -z "$CP" ] && CP="$CP:"
		CP="$CP$TMP"
	    fi
	done
	echo $CP
	;;
    *)
	echo -e "How this could happen!?\nCall the police!"
	exit 1
	;;
esac

exit 0
