#!/bin/ksh




###!/bin/csh -f
##
##
## Copyright (C) Comunicacion Integral, Las Palmas de Gran Canaria, 1997
##
##
##
#if (! $?TREEROOT) then
#  echo \$TREEROOT not set
#endif
#
### don't run as root (testing for $USER doesn't work after su )
##id | fgrep -s root
##if ( ! $status  ) then
##  echo you should not run this script as root
##  exit 1
##endif
#
#unset example
## command line parsing
#  set arguments = `getopt ha: $*`
#  if ( $status != 0 ) then
#    set arguments = ( '-h' '--' )
#  endif
#  while ( "$arguments[1]" != "--" )
#    set option=$arguments[1]
#    shift arguments
#    switch ( $option ) 
#      case '-a':
#        set example=$arguments[1]
#        shift arguments
#        breaksw
#      case '-h':
#	echo 'usage: tgz [-h]'
#	exit 1
#    endsw
#  end
## now shift the -- out of the way
#shift arguments
#
##if( $#arguments < 1 ) exit
#
##if (! $?example ) then
##  echo no option -a given
##  echo usage: tgz -a optionarg arguments
##  exit
##endif
#
##echo $arguments







#
# tgz Utility v0.2
#
# written by Martin Mielke for Jaleo, a division of Comunicacion Integral Consultores
# (c) Comunicacion Integral Consultores, Las Palmas de Gran Canaria
#



#
# Functions
#

function usage
{
        echo "Usage:\ttgz [-h] [-l] [-x] [-c] targetname sourcefile1 sourcefile2 ..."
	echo "\t-h  Prints this help."
        echo "\t-l  Lists the contents of a tgz file."
        echo "\t-x  Extracts contents from a tgz file relative to the current working directory."
	echo "\t-c  Creates a tgz file. First argument is the destination filename."
        exit 1
}

function viewtgz
{
	if [ -r $tgzfile ]
	then
	    echo "\nViewing contents of $tgzfile ...\n"
	    gzip -d < $tgzfile | tar -tvf -
	else
	    echo "\nFile $tgzfile doesn't exist....\n"
	    exit 1
	fi
}

function extractTgz
{
        if [[ -r $tgzfile ]]
	then
	    echo "\nExtracting contents from $tgzfile ...\n"
	    gzip -d < $tgzfile | tar -xvRf -
	else
	    echo "\nFile $tgzfile doesn't exist....\n"
	    exit 1
	fi
}

function createTgz
{
	tar -cvf - $source | gzip -c | dd of=$target
}
#------------------------------------------------------
# Main
#------------------------------------------------------

if [[ $# -eq 0 ]]
then
        usage
fi

set -- `getopt hl:x:c: $*`

if [[ $? -ne 0 ]]
then
        usage
fi


for arg in $*
do
        case $arg in
        -h) usage; shift 1;;
        -l) tgzfile=$2; viewtgz; exit 0;;
        -x) tgzfile=$2; extractTgz; exit 0;;
	-c) shift 1; target=$1; shift 2; source=$*; createTgz; exit 0;;
	*) usage; exit 0;;
        esac
done


#
# The End
#

exit 0
