#!/bin/bash

# copyright: copyleft;  Diego.Saravia@gmail.com 2010
# upack 

#opcion especial para variaciones tgz de slack? rpm de suse?

# ojo requiere fakeroot y dpkg-deb

# hacer que cuando abre un paquete deb dsc src.rpm o rpm o tbz2 o tgz
# construya un .summa con la mayor cantidad de datos, para generar la base de datos de paquetes

 
#
# suele haber dos clases de paquetes, los fuente y los binarios
# los fuente suelen tener adentro un solo directorio principal con el nombre del
# paquete codificado 
# los binarios parten de la raiz del sistema teniendo /bin /sbin /usr /etc
# aqui metemos lo que encontremos adentro de DIRECTORIO

# un super alien? en bash y con mas formatos?

UPACK_PROG_NAME=upack
UPACK_PROG_VERSION=0.1
UPACK_PROG_LICENCE="AGPLv3+: GNU AGPL version 3 or later"


# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU  Affero General Public License as published by
# the Free Software Foundation; last version,  from 3 to  any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
#





##############
# el target probablemente no sea necesario ponerlo en control o spec, veamos
#echo TARGET XXXXXXXXXXXXXXX $TARGET 
###########################
#`echo $TARGET | awk -F- '{print "export arch="$1" brand="$2" system="$3" kernel="$4}'`
### $target_cpu $target_os $target_vendor
#echo TARGETS: $arch $brand $system $kernel

#exit;
#i386 i586 i686 x86_64 ppc ppc64 athlon src noarch
#suse debian redhat ututo slack none
#linux
#gnu
########################################################################### Configuration vars
upack_vars(){
#XARGS=xargs
#SOURCES="/usr/src/download"

UPACKSOURCED=1

# revisar si tomo de ahi o de otro lado pkgac.dat
if test x"$DIRBIN" = x ; then
 DIRBIN=$(summabase)
fi

if test x"$SUMMABASESOURCED" != 1; then
  source $DIRBIN/summabase source
  summabase_vars
  msg 9 "Carga summabase en uinstall"
fi
if test x"$UPACKNAMESOURCED" != 1; then
  source $DIRBIN/upackname source
  upackname_vars
fi


#$TMPDIR viene en summapack.sh

#UPACKDIR=$TMPDIR/upack
#mkdir -p $UPACKDIR
}

########################################################################### version
upack_version(){
cat <<EOF
$UPACK_PROG_NAME $UPACK_PROG_VERSION
Copyright (C), copyleft, 2010 Diego Saravia <dsa@unsa.edu.ar>
License: $UPACK_PROG_LICENCE
<http://gnu.org/licenses/gpl.html>

Funcion unpack tomada de ebuild de Fundacion Gentoo.
This is free software: you are free to change & redistribute it.
There is NO WARRANTY, to the extent permitted by law.
EOF
}

########################################################################### usage
upack_usage(){
cat <<'FINUSAGE'
Usage: 
    upack  -p TYPE NAME CONTENTS-DIR [METAINFO-DIR]
    upack  -u PACKAGEFILE CONTENTS-DIR [METAINFO-DIR] 

FINUSAGE
}
########################################################################### usage
upack_usage(){
cat <<'FINUSAGE'
Usage:

    upack  -p TYPE NAME CONTENTS-DIR [METAINFO-DIR]
    upack  -u PACKAGEFILE CONTENTS-DIR [METAINFO-DIR] 
 
Action could be:

-p type --pack=type
-u --unpack
-h --help
-v --version

if NAME=- it will look for name in METAINFO-DIR/*.summa
if METAINFO-DIR is not specified it will use default directory .

En la creacion de paquetes se empaqueta lo que hay en CONTENTS-DIR
en base a la informacion que hay (si la hay) en METAINFO-DIR, en particular:
PACKAGE.summa pkac.dat y ChangeLog, creando otros metaarchivos y contenidos
segun el tipo de paquete.

Para usar, copie en METAINFO-DIR .summa y otros y en CONTENTS-DIR los archivos
y ejecute.

En el desempaquetado coloca los contenidos del paquete en CONTENTS-DIR
poniendo en METAINFO-DIR los metarchivos segun el paqute y generando
.summa (todavia no, pensado para completar la base de datos de paquetes)

FINUSAGE
}

########################################################################### CHECKDIR
#  alertas debian

checkperms(){
#docdir = debian/tmp/usr/share/doc/$PACKAGE
#install -m 755 debian/postinst debian/prerm
#cd debian/tmp && mv usr/info usr/man usr/share
#cp -a NEWS debian/copyright $(docdir)
#cp -a debian/changelog $(docdir)/changelog.Debian
#cp -a ChangeLog $(docdir)/changelog
#cd $(docdir) && gzip -9 changelog changelog.Debian
#gzip -r9 debian/tmp/usr/share/man
#gzip -9 debian/tmp/usr/share/info/*
#dpkg-shlibdeps debian/tmp/usr/bin/hello
#dpkg-gencontrol -isp
#chown -R root:root debian/tmp
#chmod -R u+w,go=rX debian/tmp

################## alertas slack

# Warn of zero-length files:
find  $BUILD_ROOT -type f -size 0c | while read file ; do
  echo "WARNING:  zero length file $file)"
done

# Warn of corrupt or empty gzip files:
find  $BUILD_ROOT -type f -name '*.gz' | while read file ; do
  if ! gzip -t $file 1> /dev/null 2> /dev/null ; then
    echo "WARNING:  gzip test failed on $file"
  else
    if [ "$(gzip -l $file | tail -n 1 | tr -s ' ' | cut -f 3 -d ' ')" -eq 0 ]; then
      echo "WARNING:  $file  is an empty gzipped file"
    fi
  fi
done

# Some more handy warnings:
if [ -d  $BUILD_ROOT/usr/share/man ]; then
  echo "WARNING:  /usr/share/man (with possibly not gzipped man pages) detected"
fi

if [ -d  $BUILD_ROOT/usr/share/info ]; then
  echo "WARNING:  /usr/share/info (with possibly not gzipped info pages) detected"
fi


if find  $BUILD_ROOT | grep site_perl 1> /dev/null ; then
  echo "WARNING:  site_perl directory detected (this is fine for a local package build)"
fi

#####################3  PERMISOS

echo
echo "This next step is optional - you can set the directories in your package"
echo "to some sane permissions. If any of the directories in your package have"
echo "special permissions, then DO NOT reset them here!"
 

#esto lo hace el install, igual que emita warnings

CHOWN=n


if [ "$CHOWN" = "y" ]; then
  find $BUILD_ROOT -type d -exec chmod -v 755 {} \; 
  find $BUILD_ROOT -type d -exec chown -v root.root {} \;
fi


#chown -R root.root $BUILD_ROOT

#find $BUILD_ROOT -perm 777 -exec chmod 755 {} \;
#find $BUILD_ROOT -perm 555 -exec chmod 755 {} \;
#find $BUILD_ROOT -perm 444 -exec chmod 644 {} \;
#find $BUILD_ROOT -perm 666 -exec chmod 644 {} \;
#find $BUILD_ROOT -perm 664 -exec chmod 644 {} \;
}





########################################################################### MAIN



if test x"$1" != xsource ; then 

    upack_vars
    verbose=false
    ACTION=NONSET
    TYPE=NONSET
    OPTLIND=1

    while getopts_long :up:vVh opt \
     pack required_argument \
     help no_argument \
     unpack no_argument \
     usage no_argument \
     verbose no_argument \
     version no_argument \
     "" "$@"
     do
       case "$opt" in
		h|help|usage) 
                     upack_usage
                     exit 
                      ;;
		V|version) 
                     upack_version 
                     exit
                       ;;
                v|verbose) 
                     verbose=true
                       ;;
                p|pack)
                     ACTION=pack
                     TYPE=$OPTLARG
                      ;;
                u|unpack)  
                     ACTION=unpack
                      ;;
                :) printf >&2 '%s: %s\n' "${0##*/}" "$OPTLERR"
                     upack_usage
          exit 1;;
     esac
 done
 shift "$(($OPTLIND - 1))"
  

PACKAGE=$1

if test x"$PACKAGE" = x ; then
   msg 4 "No especifico el primer argumento: package_name"
   upack_usage
   exit 
fi


PACKAGE2=$(echo "$PACKAGE" | sed -e "s/ /-/g" | sed -e "s/[ \t]//g")
if test  $PACKAGE2 != $PACKAGE; then
    echo "Cambiar nombre del paquete"
    exit
fi


UPACKDROOT=$2
if test x"$UPACKDROOT" = x ; then
   msg 4 "No especifico el segundo argumento: directory with/for contents"
   upack_usage
   exit
   
fi



UPACKDINFO=$3

if test x"$UPACKDINFO" = x ; then
  UPACKDINFO=`pwd`
fi

#////////////////////////////////// pkginfo

######################3 en debian hacer archivo dsc

#if test "x$1" != "x"; then
#   BUILD_ROOT=$1
#fi

#instala un paquete en DESTDIR=$BUILD_ROOT
#y genera archivos de informacion con los archivos instalados para diferentes distros

#BUILD_ROOT debe venir definido de afuera pues alli deben ser tomados los archivos para los
#empaquetadores

#BUILD_ROOT debe estar dentro de /tmp o similar
# hacer check para que lo este en /tmp y ademas en $TMP_DIR, eso implica que  TMP_DIR en /tmp

#BUILD_ROOT sera vaciada

# si no esta BUILD_ROOT se crea en /$TMP_DIR/azar

#debemos estar en raiz de ese proyecto, y debe haber archivos $PACKAGE.summa y pkgac.dat

#if test ! -e ./configure ; then
#  echo No hay ./configure aqui
#  exit
#fi

# a veces cuando se lo llama desde makefile y como root, no tiene en el path /usr/local/bin
# a veces estos paquetes se instalan ahi
# solucion precaria
PATH=$PATH:/usr/local/bin


#ojo configurar asi el make install con destdir
#./configure --prefix=/usr --sysconfdir=/etc --localstatedir=/var
# install-strip




if test "x$TMP_DIR" = "x"; then
  #echo Variable TMP_DIR: $TMP_DIR, vacia, la pongo en /tmp
  TMP_DIR=/tmp 
fi

echo "Tmpdir: $TMP_DIR"


################# instala paquete

#make DESTDIR=$BUILD_ROOT install


#TMP_DIR directorio de trabajo
#BUILD_ROOT directorio de instalacion
#uno adentro del otro
# hacer afuera

######################################################################################33




###################################################### PACK
if test x"$ACTION" = xpack ; then
# busca .summa, pkgac.dat y ChangeLog en el mismo dir DIRSUMA
# ChangeLog en packlets.


  if test x"$TYPE" = x -o x"$TYPE" = xNONSET ; then
   msg 4 "No especifico  type"
   upack_usage
   exit
  fi

  if test  x"$PACKAGE" = x"-" ; then
      #buscar en UPACKDROOT un unico .summa
      CANTSUMA=`ls -1 $UPACKDINFO/*.summa|wc -l` # si no hay suma da un error tonto, arreglar
      if test x"$CANTSUMA" = x1 ; then 
        SUMMAFILE=`ls -1 $UPACKDINFO/*.summa`
        PACKAGEFILE=`echo $SUMMAFILE| sed -e 's/\.summa$//'`
        . $PACKAGEFILE.summa
        PACKAGE=`basename $PACKAGEFILE`  
        LEIDOSUMMA=$PACKAGEFILE.summa
        msg 4 "Leido $LEIDOSUMMA"  
        else
         LEIDOSUMMA=''
         msg 4 "No hay un summa unico en $UPACKDINFO"
         exit
      fi 
  else
         LEIDOSUMMA=''
 fi

######### sacar
#VERSION RELEASE HOST TARGET BUILD PREFIX?????
# verificar PACKAGE
  DIRSUMA=$(dirname "$LEIDOSUMMA")
  if test x"$DIRSUMA" = x ; then 
     DIRSUMA=.
  fi

  if test  -e $DIRSUMA/pkgac.dat;  then
    . $DIRSUMA/pkgac.dat
     msg 4 "Leido $DIRSUMA/pkgac.dat" 
  else
     msg 4 "No hay archivo  pkgac.dat junto con $PACKAGE.summa"
  fi

  ################33 OJO LUEGO rpm-base deb-pack y dsc-pack leeran 
  ################   $DIRSUMA/ChangeLog


  if test x"$RELEASE" = x0 -o  x"$RELEASE" = x ; then
     echo "RELEASE=0 is not aloud in debian, change .release file and run ./configure"
     RELEASE='0.1'
  fi

  if test x"$VERSION" = x0 -o  x"$VERSION" = x ; then
     echo "0 is not aloud in debian, change .release file and run ./configure"
     VERSION='0.1'
  fi


   #echo "empty RELEASE is not aloud, change .release file and run ./configure"
   # ver caso de paquetes no paquetes :)

  
  # second arg bin type is usually included in $PACKAGE if binary REVISARRRRRRRRR
  # PASAR HOST a los paquetes binarios, donde se ejecutaran 
  #The build platform is where the code is actually compiled. The host platform is where the compiled code will execute. 
  #The target platform usually only applies to compilers.
  # It represents what type of object code the package itself will produce (such as cross-compiling a cross-compiler);
  # otherwise the target platform setting is irrelevant. For example, consider cross-compiling a video game that will
  # run on a Dreamcast. The machine where the game is compiled is the build platform while the Dreamcast is the host platform.

  # for source package in deb use TYPE dsc
#Architecture: The architectures for which the binary package(s) will be built. Examples are:
#    * all - The source is not architecture-dependent. Programs that use Python or other interpreted languages would use this. The resulting binary package would end with _all.deb.
#    * any - The source is architecture-dependent and should compile on all the supported architectures. There will be a .deb file for each architecture (_i386.deb for instance)
#    * A subset of architectures (i386, amd64, ppc, etc.) can be listed to indicate that the source is architecture-dependent and does not work for all architectures supported by Ubuntu. 

##########3 lo hace el configure, tomar de ahi la info sobre ARCH Y DEBARCH
  if test x$SPECIALARCH != x ; then
    ARCH=$SPECIALARCH # en .summa
   else
    # host es autodetecato en configure o incorporado como parametro con --host
    ARCH=`echo $HOST | awk -F- '{print $1}'`
  fi
  #MARCHITECTURE esta en infosis pero no parece estar AC_SUBST, mejor HOST que se define en --host durante ./configure
  #echo $MARCHITECTURE - $HOST - $ARCH

############################3
#Si no hay HOST en .summa del paquete buscar el de la maquina detectado en la instalacion de
#sumapack

#############################

  createpackname $PACKAGE "" "$VERSION" "$RELEASE" "$ARCH" "" "" "$TYPE"
  
  PKGNAME=$CN_PKGNAME
  echo PKGNAME $PKGNAME

  #upackname $PKGNAME  # como forma de probar si calcula bien el nombre

  #$VERSION-$RELEASE-$host
 

  # verificar existencia de ROOT si no salir, verificar que hay algo
   if test ! -d "$UPACKDROOT" ; then 
       msg 4 "no hay $UPACKDROOT"
       exit
   fi 

   CANTEX=`ls -1 $UPACKDROOT |wc -l`
   #echo NNNN $CANTEX 
   if test x"$CANTEX" = x0 ; then 
     msg 4 "Directorio $UPACKDROOT vacio"
     exit
   fi 
 
  # verificar existencia de INFO si no crearlos

   if test x"$UPACKDINFO" = x ; then
      UPACKDINFO=$(mktemp -d $TMP_DIR/pkginfo.XXXXXX)      
      msg 4 "Definiendo y creando directorio INFO: $UPACKDINFO"
   elif test ! -d $UPACKDINFO ; then 
      mkdir -p $UPACKDINFO
      msg 4 "Creando directorio INFO: $UPACKDINFO"
   else
      :
   fi

   SALESVN=`find $UPACKDROOT -name ".svn"`
   if test x"$SALESVN" != x ; then
       msg 4 "El directorio $UPACKDROOT esta bajo control de versiones"
       exit

   fi
   SALESVN=`find $UPACKDINFO -name ".svn"`
   if test x"$SALESVN" != x ; then
       msg 4 "El directorio $UPACKDINFO esta bajo control de versiones"
       exit

   fi
###################################################### UNPACK

elif test x"$ACTION" = xunpack ; then

############ ojo, cambiar en pack el PKGNAME es con extension
# aca sin, ponerla

   if test -e "$PACKAGE" ; then 
     extsep $PACKAGE
     # recibe $PACKEXT $PACKNOEXT - $PACKTYPE
     TYPE=$PACKEXT
     PKGNAME=$PACKNOEXT
     # usar upackname
    else
      msg 4 "No hay archivo donde se indica el paquete"
      exit
   fi



else
  echo Bad ACTION: $ACTION
  exit;
fi



PREFIX=`echo $DIRBIN | sed -e 's/\/bin$//'`
#/usr/local/bin
#echo DIRBIN $DIRBIN - PREFIX: $PREFIX
packlet=$PREFIX/share/sumapack/packlet
#packlet=/home/dsa/oooo/dsatex/sumapack-nuevo/remote/svn/trunk/sumapack-ini/scripts/upack/packlet

pro="$packlet/$TYPE-$ACTION.sh";
if test ! -e "$pro" ; then 
   # asume la responsabilidad por todos los formatos sin packlet especial
   pro="$packlet/tarballs-$ACTION.sh $TYPE";
fi



msg 7  "process  $ACTION, $PKGNAME, $TYPE, $UPACKDROOT, $UPACKDINFO, PACKLET: $pro"
echo  "process  $ACTION, $PKGNAME, $TYPE, $UPACKDROOT, $UPACKDINFO, PACKLET: $pro"

# $TYPE $PACKAGE $PKGNAME $UPACKDROOT $UPACKDINFO

. $pro




fi


exit


########################################################################### MAIN_END

# tomado de ebuild, gentoo

#ROOTDIR=`pwd`
#PORTAGE_BUILDDIR=$ROOTDIR/${P}
#UNPACKDIR=$ROOTDIR
#UNPACKED=$PORTAGE_BUILDDIR
#echo GGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGG $UNPACK
#if test "x$UNPACK" = x1; then
#   echo GGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGG
#   UNPACKDIR=$PORTAGE_BUILDDIR
#   UNPACKED=$PORTAGE_BUILDDIR/unpack
#fi

#echo ROOT: $ROOTDIR - $UNPACKDIR - $UNPACKED


#UNPACKED
#UNPACKDIR
#P
#PF 	Full package name, ${PN}-${PVR}, for example vim-6.3-r1.
#PF=${PN}-${PV}  #ver sufijo
#if test ! -z "${PR}"; then 
#   PF=${PN}-${PV}-${PR}
#fi
#UNPACK=1 ;; # por defecto es 0, o sea esta en ROOT/nombre, si se coloca queda en ROOTDIR/nombre/unpack
#        	rm -rf "${UNPACKED}"
#	if [ ! -d "${UNPACKDIR}" ]; then
#		install -m${PORTAGE_WORKDIR_MODE:-0700} -d "${UNPACKDIR}" || die "Failed to create dir '${UNPACKDIR}'"
#	fi
#	cd "${UNPACKDIR}" || die "Directory change failed: \`cd '${UNPACKDIR}'\`"


#UNPACKTEMP=$ROOTDIR/${P}.tmpunpack
#rm -r $UNPACKTEMP
#mkdir -p $UNPACKTEMP
#cd "${UNPACKTEMP}" || die "Directory change failed: \`cd '${UNPACKTEMP}'\`"


        # esta posicionado donde desempacar


####################3


	# Do not chmod '.' since it's probably ${WORKDIR} and PORTAGE_WORKDIR_MODE
	# should be preserved.

#ver
#	find . -mindepth 1 -maxdepth 1 ! -type l -print0 | \
#		${XARGS} -0 chmod -fR a+rX,u+w,g-w,o-w


#if test "x$UNPACK" = x1; then
#  echo UUUUUUUUUUUUUUUUU ${UNPACKTEMP}/${P} ${UNPACKDIR}
#  mv ${UNPACKTEMP}/${P} ${UNPACKED}
# else
#  #echo ${UNPACKTEMP}/${P} ${UNPACKDIR}
#  mv ${UNPACKTEMP}/${P} ${UNPACKDIR}
#fi
#rmdir $UNPACKTEMP
# desempaqueta en forma segura
#prueba de que el soft se desempaqueta en un directorio con el nombre adecuado
# se puede calcular el nombre

#

# para compilar luego
#        WORKDIR=$UNPACKED   





#EXTENSIONES="ebuild ubuild summa tar.gz tgz tar.bz tar.bz2 tbz tbz2 ZIP sip jar gz Z z bz2 bz 7Z 7z RAR rar LHa LHA lha lzh a deb lzma xz rpm"


#ARGUME=$PACKAGE
#for uext in $EXTENSIONES ; do
#   nuext=`echo $uext | sed  's|\.|\\\.|' `
#   ESres=`echo $ARGUME | sed "s/\.$nuext\$//"` 
#   if test "x$ESres" != "x$ARGUME"; then
#      ext=$uext
#      ARGUME=$ESres
#      break 
#   fi
#done



# ojo si tienen BUILD_ROOT o TMPDIR

#PACKAGE_NAME="$1"
#TARGET_NAME="$(dirname $PACKAGE_NAME)"
#PACKAGE_NAME="$(basename $PACKAGE_NAME)"
#EXTENSION="tgz tbz txz"
#TAR_NAME="$(basename $PACKAGE_NAME .$EXTENSION)"







#ver si es ahi
#FILEEBUILD=$TMP_DIR/$PACKAGE.ebuild

#slack
# ver estos estan puestos directamente en distrib, no van a las fuentes?


#FILESLACKS=./$INSTALL/slack-desc
#FILECONTROLS=./$DEBIAN/control
#FILERULESS=./$DEBIAN/rules



# el makefile.am indica que debe ser distribuida, ver si se mete en el momento oportuno
# ojo hay un lsm.in, cual queda?

# spec y control tambien al fuente o solo a la distro?

# si httpdroot = /tmp no distribuir esos archivos cambiar dist-hook

#echo $FILESPEC
#exit

#echo pbn: $PKG_BASENAME

#de makepkg  echo "Slackware package maker, version 3.14159."
# de checkinstall  v1.6.1  Copyright (C) 2004 Felipe Eduardo Sanchez Diaz Duran <izto@asic-linux.com.mx>



# Calacular Instaled size 

#DIRECTORIO_FUENTE=`pwd`

#PAGER=less
#no usamos ni en debian: sensible-pager

#calcular esto
#TARSIZE=10M



#SPEC_PATH=${PACKAGE}.spec  al vicio


#echo $VERSION - $RELEASE

##### ver esta comprobacion
# Use only ascii characters: a-z e - o _
# the SPACE will be replaced by -, and TAB removed


# vamos a hacer todo el proceso configure, make, make install,del rpm aunque seria bueno que el rpm no haga esto, sino directamente tome los archivos  de un directorio 


# Sanity check -- we can't make the package in the current directory:
# buildroot no es este directorio
#if [ "$CWD" = "$TARGET_NAME" -o "." = "$TARGET_NAME" ]; then
#  echo "ERROR: Can't make output package in current directory."
#  exit 2
#fi





#USER=`whoami`
#if test "x$USER" = "xroot" ; then
#    echo ok es root.
#else
#    echo NO ES root
#    
#    exit
#fi

# sacar los sudo si esto debe correrse sudo todo
# verificar que hiciste sudo make y no make en el makefile
########no PKG_BASENAME="`basename \"$DIRECTORIO_FUENTE\"`"
######### reemplazar con .in o algo asi


#nombre-versionfuente-host-buildversionnumber.extension





#exit



#echo UPACKINSTALLDIR $UPACKINSTALLDIR



#  eval set -- "$(getopt -o hvput: --long help,version -- \"$@\")"#
#
#    while true ; do#
#	case "$1" in
##
#		*) echo "Bad Parameter!>: $1"
#                   upack_usage; 
#                    exit 1 
#                     ;;#
#	esac
#    done
#    shift `expr $OPTIND - 1
#    # resto con $*

#    while getopts "hvpu" OPTION; do
#        case $OPTION in
#            h   )   upack_usage 
#                    exit 0                            ;;        
#            v   )   upack_version
#                    exit 0                            ;;     
#            p   )      ACTION=pack
#                       ;;
#            u   )      ACTION=unpack
#                       ;;
#            \?  )    upack_usage           
#                     exit 1 ;; 
#            *  )    upack_usage           
#                     exit 1 ;; 
#        esac
#      done
#      shift $((OPTIND - 1))

#    echo "upack_main $ACTION $@"
#    upack_main $ACTION $@



