#!/bin/sh
#
# For debug: add -x on the first line above.
#
#------------------------------------------------------------------------------
#                                U&R Consultores                               
#                                www.uyr.com.ar 
# Archive  : saveit
# Creation : 19991016 - Francisco Mancardi - (FM)                      
# Revision : 
#
#            20010924  SB/TD : Use $USER and not "whoami"
#
#            20010212  FM
#                      Added configuration file
#
#            20010211  FM
#                      fixed problems with: 
#                                          saveit .
#                                          saveit ..
#
#            20010208  FM
#                      Added option -s (suffix_only) 
#                      Solaris version of test doesn't like negative
#                      numbers in -ne.
#
#            20010205  FM
#                      Added detection of readonly backup base dir
#
#            20001105  FM
#                      Adding init_messages
#                      Test the existence of traget to backup
#
#            20000729  FM
#                      Adding functions to improve code.
#                      Adding screen messages.   
#
#            20000710  FM
#                      Added option -c (Comment).
#                      You can add a comment line (why did I save this file)
#                      that will be added to the log file. 
#                            
#                      Added test:
#                      is $# -ne 0, AFTER processing options via getopt ?
#                            
#                      Added version string  
#
#                      Detected problems with 'who am i' and mc
# 
#                      Midnight Commander on Linux 6.0 if logged as root.                  
#
#            20000703    SB  (Sean Boran)
#                            english notes, tested on Sol2.7, OpenBSD 2.6
#                            If file has been save today already, save with time.
#                            (We need more testing after these changes)
#                            To Do: handle devices, links, etc.
#            20000403-01 FM
#            detecto el S.O. para saber que usar como awk
#
#            19991019-02 FM
#            Descubro el siguiente error:
#            save /etc/rc?.d/KAK -> el archivo KAK no existe, luego lo
#                                   que el shell expande y me manda como
#                                   DEST_DIR resulta ser la lista :
#                                   /etc/rc0.d /etc/rc1.d ... /etc/rcS.d 
#                                   Esto causaba la falla de un test.
#            Sin embargo si funcionaba bien:
#            save /etc/rc?.d/README ya que existen tres de estos archivos
#
#            19991019-01 FM
#            - voy a controlar antes de salvar algo, si existe.
#            - hago siempre append en el archivo de lista de operaciones
#            19991017 - FM 
#            1) agrego como argumeno opcional el directorio de base donde 
#               hacer el backup.
#            2) Se puede indicar el pathname de lo que se desea salvar
#            3) Se puede indicar que salve un directorio completo.
#               Atencion!: 
#                          en este caso se lleva TODOS los subdirectorios
#                          que tenga dentro. 
#------------------------------------------------------------------------------
#
#
# ********************************************************************************
# Configurable options
# *****************************************************************************
# Configuration file
SAVEIT_CFG="/etc/saveit.conf"; export SAVEIT_CFG

# Directory under which all backups will be stored
DIR_ROOT_BACKUP="/Backup.d"; export DIR_ROOT_BACKUP

#
FECHAHORA=`date '+%Y%m%d-%H:%M'`; export FECHAHORA
FECHA=`date '+%Y%m%d'`;          export FECHA
DD_MM_AAAA=`date '+%d-%m-%Y'`;   export DD_MM_AAAA
HH_MM=`date '+%H:%M'`;           export HH_MM

# Subdirectory format YYYYMMDD-HH:MM
TAG_BACKUP_PARANOIC=${FECHAHORA}; export TAG_BACKUP_PARANOIC

# format YYYYMMDD
TAG_BACKUP=$FECHA;                export TAG_BACKUP

# Prefix for log file in backup directory
PREFIJO_LISTA="log";              export PREFIJO_LISTA
# ***** End of configurable options *******************************************


# WITH_DEBUG=0 => debug function do nothing
# WITH_DEBUG=1 => debug function print arg on screen
WITH_DEBUG=0; export WITH_DEBUG

# general constants
CURRDIR=`pwd`;                   export CURRDIR
HOST=`hostname`;                 export HOST
PROGRAM_NAME=`basename $0`;      export PROGRAM_NAME

# Status codes
STAT_KO=99; export STAT_KO
STAT_CONTINUE=98; export STAT_CONTINUE
STAT_OK=0; export STAT_OK

# Error codes
ERROR_CANT_CREATE_DIR=3; export ERROR_CANT_CREATE_DIR
ERROR_CANT_WRITE_ON=4; export ERROR_CANT_WRITE_ON 
ERROR_MAKE_COPY=8; export ERROR_MAKE_COPY



# +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
#                           Begin Auxiliary Functions
# +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
#
# ........................................................................
# set the text of the messages
# ........................................................................
init_messages()
{

# Messages
MSG_NOT_FOUND="File/Dir doesn't exists - no backup made";
export MSG_NOT_FOUND

MSG_CANT_CREATE_DIR="Can't create directory: ";  export MSG_CANT_CREATE_DIR

MSG_CANT_COPY="Can't copy: ";           export MSG_CANT_COPY

MSG_CANT_WRITE_ON="Can't write on: (is read only ?)"
export MSG_CANT_WRITE_ON


MSG_COPYING="copying ";                 export MSG_COPYING
MSG_COPYING_FILE="copying file ";       export MSG_COPYING_FILE
MSG_COPYING_DIR="copying directory ";   export MSG_COPYING_DIR

MSG_I_D_NOT="options -i and -d not allowed together"; export MSG_I_D_NOT
MSG_I_O_NOT="options -i and -o not allowed together"; export MSG_I_D_NOT
MSG_NOT_TOGETHER="options not allowed together: "; export MSG_NOT_TOGETHER

MSG_DIR_LIST="Directory listing: ";     export MSG_DIR_LIST
}
# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++


# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
debug()
{
if [ $WITH_DEBUG -eq 1 ]; then
    echo $1
fi
}

# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++


# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
# Function: usage
#           shows usage instructions on screen
#
# Arguments: optional message
#
# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
usage()
{

VERSION="2.4.4"

PROGNAME=`basename $0`

# aca levanto el argumento
MENSAJE=$1

#${MENSAJE}

cat << EOF

${PROGNAME} - Simple Backup Utility - v$VERSION

usage
${PROGNAME} [OPTION] Pathname

Options

-a plain.
   The file/directory to be saved is copied in the 
   Base Backup Directory without creating the standard 
   YYYYMMDD directory and without creating the target 
   fullpath.
   If target exists, a new target is created and 
   renamed appending .HH:MM to the original name.
   Not allowed with options -s, -i.

-c comments to write into the log file

-d Base Backup Directory.
   Is used instead of the default directory /Backup.d
   Not allowed with option -i

-i backup in place
   creates a file/directory copy in the directory
   from where you are running saveit  
   The name of the saved file/directory is created 
   appending .YYYYMMDD-HH:MM to the original name.
   Not allowed with option -d, -a, -s, -o.

-o overwrite
   The file/directory to be saved is copied in the 
   Backup Directory without appending .HHMM 
   to the original name, then if the file exists in 
   the backup area it will be overwritten.
   Not allowed with option -i.

-s suffix only.
   The file/directory to be saved is copied in the 
   Base Backup Directory without creating the standard 
   YYYYMMDD directory, allways adding the suffix i
   .YYYYMMDD-HH:MM to the original name.
   Not allowed with option -a, -i, -o.

Configuration File
You can set your preferences in the file /etc/saveit.conf.

The precedence in option analysis is:
1. If an option is set in the command line this is the value used.
2. If an option is not set in the command line and is set in the
   configuration file this value is used.
3. If an option is not set either in the command line or in the
   configuration file, the default built-in value is used. 

EOF

}
# ........................................................................


# ........................................................................
# makes the copy
# ........................................................................
# 20010207 - the Solaris version of test doesnt like negative numbers
#
# -----------------------------------------------------------------------
# Arguments:
#           SOURCE_FILENAME
#           ABS_SOURCE_PATHNAME
#           DEST_DIR
#
#
#
make_copy()
{

# get arguments
my_sf=$1
my_asp=$2
my_ddir=$3

# -----------------------------------------------------------------------
debug "make_copy $COUNT"
debug "my_sf, my_asp, my_ddir"
debug "$my_sf, $my_asp, $my_ddir"
# -----------------------------------------------------------------------

# -----------------------------------------------------------------------
# source exists ?
if [ -f $my_asp -o -d $my_asp ] 
then
   cmd_status=0
else
   cmd_status=$ERROR_MAKE_COPY
   return $cmd_status
fi
# -----------------------------------------------------------------------

DEST_FILE=$my_ddir/$my_sf

if test $save_over -eq 0
then
   # standard way, add the sufix
   DEST_FILE=$my_ddir/$my_sf.$SUFFIX
fi

# ****************************************************
# strip multiples /
#'s-/*/-/-g'
my_dir_destino=`echo $my_ddir | sed 's-/*/-/-g'`
my_target_file=`echo $my_sf | sed 's-/*/-/-g'`
my_tfile=`echo $my_asp | sed 's-/*/-/-g'`
my_dest_file=`echo $DEST_FILE | sed 's-/*/-/-g'`
my_test_arg=$my_ddir/$my_sf
my_test_arg=`echo $my_test_arg | sed 's-/*/-/-g'`
# ****************************************************


## Sean
## If target exists already, save to target.SUFFIX
if [ -f $my_test_arg ]; then

   # target is a FILE and exists, so add time to target
   echo $MSG_COPYING_FILE "$my_tfile ===> $my_dest_file"

   cp -Rp $my_tfile $my_dest_file 2>/dev/null

elif [ -d $my_test_arg ]; then
   # target is a Directory and exists, so add time to target
   echo $MSG_COPYING_DIR "$my_tfile ===> $my_dest_file"

   cp -Rp $my_tfile $my_dest_file 2>/dev/null

elif [ -f $my_tfile -a -f $my_test_arg ]; then

   # source is a directory/file construction and target already exists
   echo $MSG_COPYING_FILE "$my_tfile ===> $my_dest_file"

   cp -Rp $my_tfile $my_dest_file 2>/dev/null

elif [ $suffix_only -eq 1 ]; then

   # in this case allwasys use prefix
   echo $MSG_COPYING "$my_tfile ===> $my_dest_file"
   cp -Rp $my_tfile $my_dest_file 2>/dev/null

else
    #if [ $my_sf = "." -o $my_sf = ".." ];then
   echo $MSG_COPYING "$my_tfile ===> $my_dir_destino/$my_target_file"

   # esta bien que el echo diga una cosa y el comando sea otro, por
   # problemas de copia con directorio ???
   #
   debug "cp -Rp $my_tfile $my_dir_destino 2>/dev/null"
   cp -Rp $my_tfile $my_dir_destino 2>/dev/null
fi

# we are returning cp status
cmd_status=$?
return $cmd_status
}
# ........................................................................

#
# 20001105
ls_2_log()
{
#get argument
TFILE=$1

`ls -la $TFILE | $AWKNAME  'BEGIN {RIGHTS=1; USER=3; GROUP=4; F_NAME=9; 
                                                  ARROW=10; LINK=11} 
{

if( ($1 != "total") && (length($1) != 0) && 
    ($F_NAME != ".") && ($F_NAME != "..") ){

  if( index($1,"l") != 0 ){
    printf "%s %s/%s %s %s %s\n", $RIGHTS, $USER, $GROUP, 
                                     $F_NAME, $ARROW, $LINK
  }
  else {
    printf "%s %s/%s %s \n", $RIGHTS, $USER, $GROUP, $F_NAME
  }
}
}' >> $LISTA`

}
# ........................................................................


# ........................................................................
# list_2_log:
# make a listing resembling tar -t
# ........................................................................
list_2_log()
{
#get argument
TFILE=$1

`ls -lAR $TFILE | $AWKNAME -v BASE_DIR=$TFILE 'BEGIN {RIGHTS=1; USER=3; GROUP=4; F_NAME=9; 
                                                  ARROW=10; LINK=11} 
{
if (NR == 1 ) {
   prefix=BASE_DIR
}

if( ($1 != "total") && (length($1) != 0) && 
    ($F_NAME != ".") && ($F_NAME != "..") ){

  if( index($1,":") != 0 ){
      no_colon=substr($1,1,(length($1)-1))
      prefix=""
      prefix=no_colon
  }
  else if( index($1,"l") != 0 ){
    printf "%s %s/%s %s/%s %s %s\n", $RIGHTS, $USER, $GROUP, prefix, 
                                     $F_NAME, $ARROW, $LINK
  }
  else if( index($1,"d") != 0 ){
    # Add final / to mark directory
    ### printf "%s/%s/\n", prefix, $F_NAME
  }
  else {
    printf "%s %s/%s %s/%s \n", $RIGHTS, $USER, $GROUP, prefix, $F_NAME
  }
}
}' >> $LISTA`

}
# ........................................................................


# ........................................................................
# strip ./ or ../ if the string begins with one of them.
# ........................................................................
strip_dot_slash()
{
_WHERE=$1

RET_dot_slash=`echo $_WHERE | 
               $AWKNAME '{ sub("^\./","",$0); sub("^\.\./","",$0); printf "%s", $0}'`

export RET_dot_slash 
}
# ........................................................................

# ........................................................................
# transform // in /
# ........................................................................
one_slash()
{

RET_one_slash=`echo $_WHERE | 
               $AWKNAME '{ sub("//","/",$0); printf "%s", $0}'`

export RET_one_slash 
}
# ........................................................................





# ........................................................................
my_dirname ()
{
_IN_ARG=`echo $1 | sed 's-/$--'`

RET_my_dirname=` echo $_IN_ARG |
                $AWKNAME 'BEGIN { FS="/" }
                { if( NF == 1 ){ 
                      if ( $1 == ".." ) { print ".." } else { print "." }
                  }
                  else if( NF == 2 ){ if( $1=="") { printf "/" } else { printf"%s",$1 }
                  }
                  else { for(idx=1; idx < (NF-1); idx++){ printf"%s/",$idx }
                         printf"%s", $(NF-1)
                  }
                }'`
export RET_my_dirname 
}
# ........................................................................

# ........................................................................
my_basename()
{
# suppress final / if exists 
_IN_ARG=`echo $1 | sed 's-/$--'`

RET_my_basename=`echo $_IN_ARG | $AWKNAME 'BEGIN {FS="/" } {print $NF}'`

export RET_my_basename 
}
# ........................................................................

# ........................................................................
#
# returns: .   if dir= .   or starts with ./
#          ..  if dir= ..  or starts with ../ 
#
is_relative()
{
#
#echo $1 > /tmp/saveit.2222

RET_is_relative=`echo $1 | $AWKNAME '{ if( index($1,"./")== 1 || $1==".") {
                                print "."
                           }
                           else if( index($1,"../") == 1 || $1=="..") {
                                print ".."
                           }
                           else {
                                print "*"
                           }
                           }'`

export RET_is_relative 
}
# ........................................................................

# ........................................................................
# put log header
# ........................................................................
put_log_header()
{

cat >> $LISTA << EOF
--------------------------------------------------------------
Backup base directory $DIR_ROOT_BACKUP
Backup requested by   $LOGIN_ID 
Date (dd/mm/aaaa)     $DD_MM_AAAA     Time $HH_MM
EOF

if [ $HAVE_COMMENT -eq 1 ] 
then
   echo "   "          >> $LISTA
   echo "Details               "$COMMENT_LINE  >> $LISTA
fi
# ------------------------------------------------------------
}

# ........................................................................
firstdir ()
{
# no que ni lo que hice !!!
_IN_ARG=`echo $1 | sed 's-/$--'`

RET_firstdir=` echo $_IN_ARG | $AWKNAME 'BEGIN {FS="/"} {printf"%s", $2}'`
export RET_firstdir 
}
# ........................................................................




# +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
#                            End  Auxiliary Functions
# +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
#

# +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
# +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
#                              MAIN BODY
# +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
# +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
init_messages

# ......................................
# read configuration file, is exists.
if [ -f $SAVEIT_CFG ]
then
    . $SAVEIT_CFG
fi
# ......................................


# Detect os and set awk path accordingly
# 20000710 - Detected problems with 'who am i' and mc 
#            Midnight Commander on Linux 6.0 if logged 
#            as root.
#

#if [ -z "$MC_CONTROL_FILE" ]
#then
#   # no mc
#   WHOAMI="who am i" 
#else
#   WHOAMI="whoami" 
#fi
WHOAMI=$USER

OSNAME=`uname -s`;export OSNAME
if [ $OSNAME = "Linux" ] ; then
   AWKNAME="awk";export AWKNAME;

elif test $OSNAME = "SunOS" ; then 
   AWKNAME="nawk";export AWKNAME;

   if [ -z "$MC_CONTROL_FILE" ]
   then
     # no mc
     WHOAMI="/bin/who am i" 
   else
     WHOAMI="/usr/ucb/whoami" 
   fi
else
   # hope for the best
   AWKNAME="awk";export AWKNAME;
fi

COMMENT_LINE=""
HAVE_COMMENT=0
LOGIN_ID=`$WHOAMI | $AWKNAME '{ print $1 }'`; export LOGIN_ID 

# permisos
RWXR_XR_X=0755; export RWXR_XR_X

# suffix to add to identify different versions of the same file
SUFFIX=$HH_MM; export SUFFIX

# Control de argumentos.
# Si la cantidad es 0 => mostrar usage()
#
QTA_ARG=$#; export QTA_ARG
#
# -ne : solo para enteros
#
if test $QTA_ARG -eq 0 
then 
#
  usage " "
  exit 1
fi

# ----------------------------------------------------------------------
# parse command line
OPT_SAVE_OVER="o"
OPT_SAVE_PLAIN="a"
OPT_SAVE_INPLACE="i"
OPT_SAVE_DIR="d"
OPT_SUFFIX_ONLY="s"
OPT_COMMENT="c"


#OPCIONES="d:c:aios";export OPCIONES
OP1=$OPT_SAVE_DIR":"$OPT_COMMENT":"$OPT_SAVE_INPLACE
OP2=$OPT_SAVE_OVER""$OPT_SAVE_PLAIN""$OPT_SUFFIX_ONLY
OPCIONES=$OP1""$OP2;export OPCIONES

# init
save_plain=0   ; export save_plain
save_inplace=0 ; export save_inplace
save_dir=0     ; export save_dir
save_over=0    ; export save_over
suffix_only=0  ; export suffix_only 

while getopts $OPCIONES opt
do
  case $opt in

       a) save_plain=1
          ;;

       i) save_inplace=1
          SUFFIX=$FECHAHORA; export SUFFIX
          ;;

       o) save_over=1
          ;;

       d) save_dir=1
          USER_ROOT_BACKUP=$OPTARG
          ;;

       c) COMMENT_LINE=$OPTARG
          HAVE_COMMENT=1
          ;;

       s) suffix_only=1
          SUFFIX=$FECHAHORA; export SUFFIX
          ;;

       # aqui llega si se le pasa una opcion que no esta declarada
       \?)      #sleep 2 
                usage " "
                exit 2;;
  esac
done


# **************************************************************************
# if option not set, look for value set by the configuration file.
# 
if [ $save_plain -eq 0 ]; then
   if [ ! -z "$sv_save_plain" ]; then
      if [ $sv_save_plain = "1" ]; then
          save_plain=1
      fi
   fi
fi

if [ $save_over -eq 0 ]; then
   if [ ! -z "$sv_save_over" ]; then
      if [ $sv_save_over = "1" ]; then
          save_over=1
      fi
   fi
fi

if [ $save_inplace -eq 0 ]; then
   if [ ! -z "$sv_save_inplace" ]; then
      if [ $sv_save_inplace = "1" ]; then
          save_inplace=1
          SUFFIX=$FECHAHORA; export SUFFIX
      fi
   fi
fi


if [ $suffix_only -eq 0 ]; then
   if [ ! -z "$sv_suffix_only" ];then
      if [  $sv_suffix_only = "1" ]; then
          suffix_only=1
          SUFFIX=$FECHAHORA; export SUFFIX
      fi
   fi
fi


if [ $save_dir -eq 0 ]; then
   if [ ! -z "$sv_base_dir" ]; then
          save_dir=1
          USER_ROOT_BACKUP=$sv_base_dir
   fi
fi
# **************************************************************************

# --------------------------------------------
# test options not allowed togheter
# 20000812
if test $save_inplace -eq 1
then

  DIR_ROOT_BACKUP=$CURRDIR

  if test $save_over -eq 1
  then
     echo "$MSG_NOT_TOGETHER $OPT_SAVE_INPLACE and $OPT_SAVE_OVER"
     exit
  fi

  if test $save_dir -eq 1
  then
     echo "$MSG_NOT_TOGETHER $OPT_SAVE_INPLACE and $OPT_SAVE_DIR"
     exit
  fi

  if test $save_plain -eq 1
  then
     echo "$MSG_NOT_TOGETHER $OPT_SAVE_INPLACE and $OPT_SAVE_PLAIN"
     exit
  fi

  if test $suffix_only -eq 1
  then
     echo "$MSG_NOT_TOGETHER $OPT_SAVE_INPLACE and $OPT_SUFFIX_ONLY"
     exit
  fi

fi


if test $save_plain -eq 1; then
   if test $suffix_only -eq 1; then
      echo "$MSG_NOT_TOGETHER $OPT_SAVE_PLAIN and $OPT_SUFFIX_ONLY"
      exit
   fi
fi


if test $suffix_only -eq 1; then
   if test $save_over -eq 1; then
      echo "$MSG_NOT_TOGETHER $OPT_SAVE_OVER and $OPT_SUFFIX_ONLY"
      exit
   fi
fi

if test $save_dir -eq 1
then
  DIR_ROOT_BACKUP=${USER_ROOT_BACKUP}
fi
# --------------------------------------------



# Archivo donde se deja la lista de los archivos que se resguardaron.
ARCHBKPED=$PREFIJO_LISTA"-"$TAG_BACKUP; export ARCHBKPED

# con esto va a parar a $1 el primer argumento luego de todas
# las opciones
#
shift `expr $OPTIND - 1`

# 20000710 - FM
# After processing all options, is there an argument ?
# if not -> K.O.

if test $# -eq 0 
then 
#
  usage " "
  exit 1
fi


# ----------------------------------------------------------------------
# me fijo si el directorio root de backup es relativo o absoluto.
# si es relativo trato de transformarlo en absoluto 
#
#
# returns: .   if dir= .   or starts with ./
#          ..  if dir= ..  or starts with ../ 
#
is_relative $DIR_ROOT_BACKUP

# throw away ./ and ../ if present
strip_dot_slash $DIR_ROOT_BACKUP 

case $RET_is_relative in

     .)DIR_ROOT_BACKUP=$CURRDIR"/"$RET_dot_slash;;

     ..) cd ..; DIR_ROOT_BACKUP=`pwd`"/"$RET_dot_slash; cd $CURRDIR;;

     *);;
esac
# ----------------------------------------------------------------------


# ----------------------------------------------------------------------
# Ahora tengo que tratar de crear el directorio donde hacer el resguardo
# Controlo si tengo exito
#
# N.B.!!: el uso de mkdir -p tiene las siguienets ventajas:
#         1) crea directorios padres si no existen
#         2) no grita si el directorio que quiero crear existe.
#
# Al resguardar creo toda la estructura de directorio hasta llegar al
# directorio donde reside el archivo a resguardar.
# DEBO IR HASTA DONDE ESTA EL ARCHIVO DESEADO ya que uso pwd para saber
# donde estoy.
#

DIR_BASE_BACKUP=$DIR_ROOT_BACKUP

if test $save_inplace -eq 1; then
    DIR_BASE_BACKUP=$CURRDIR

elif test $save_plain -eq 1; then
    DIR_BASE_BACKUP=$DIR_ROOT_BACKUP

elif test $suffix_only -eq 1; then
    DIR_BASE_BACKUP=$DIR_ROOT_BACKUP

else 
    DIR_BASE_BACKUP=$DIR_ROOT_BACKUP"/"$TAG_BACKUP
fi
export DIR_BASE_BACKUP


# Por ahora todo O.K.
#
# Armo el nombre del archivo donde dejar la lista de los que salve
LISTA=$DIR_ROOT_BACKUP"/"$ARCHBKPED; export LISTA

# check for backup dir existence and create it, if necessary
if [ ! -d ${DIR_ROOT_BACKUP} ]; then
   mkdir -m $RWXR_XR_X -p ${DIR_ROOT_BACKUP} 2> /dev/null

   # test the result of mkdir
   if [ $? -ne 0 ];then
      echo "757 - $MSG_CANT_CREATE_DIR $DIR_ROOT_BACKUP"
      exit $ERROR_CANT_CREATE_DIR
   fi

else
   # the directory exists.
   # test if you are trying to write in a read-only filesystem
   
   my_exe=`basename $0`
   my_touch_file=${DIR_ROOT_BACKUP}"/"$my_exe.$$

   touch $my_touch_file 2> /dev/null

   if [ $? -ne 0 ];then
      echo "$MSG_CANT_WRITE_ON $DIR_ROOT_BACKUP"
      exit $ERROR_CANT_WRITE_ON
   else
      rm $my_touch_file
   fi
fi


# ------------------------------------------------------------
# Ahora voy a verificar si todo lo que me piden que 
# guarde existe.
#
# Tiene que existir por lo menos 1 para que coloque registro
# en el log.
# Podria llevar un log de errores (solo si el usario quiere).
#
# ------------------------------------------------------------
# Ahora copio los archivos
#
# variables importantes de shell (Kernighan & Pike -  The UNIX Programming Environment)
#
# $#  cantidad de argumentos (sin contar el nombre del programa)
# $*  la lista de todos los argumentos
# $-  las opciones suministradas
# $?  valor del ultimo comando ejecutado  

# init
log_h_written=$STAT_KO


COUNT="+"

for arg in $*
do
  # analizo para ver si en arg tiene directorio (distinto al ./)
  # esto sirve para hacer el backup sin tener que pararme en el
  # directorio que deseo.
  #
  # N.B.: dirname pepe     -> .
  #       dirname ./pepe   -> .
  #

  debug arg
  debug $arg

  # get dirname of arg 
  my_dirname $arg
  LISTA_DIR_ORIGEN=$RET_my_dirname; export LISTA_DIR_ORIGEN

  # get the string after the last / of arg 
  my_basename $arg
  SOURCE_BASENAME=$RET_my_basename; export SOURCE_BASENAME

  debug "LISTA_DIR_ORIGEN: $LISTA_DIR_ORIGEN"
  debug "SOURCE_BASENAME: $SOURCE_BASENAME"


  # >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
  # para que funcione algo como save /etc/rc?.d/AKA, que si no no anda 
  # debo probar mejor tengo mis dudas acerca de este for


  for DIR_ORIGEN in $LISTA_DIR_ORIGEN
  do

    # ------------------------------------------
    # manage . and ..
    # transform it in an absolute path
    if test $DIR_ORIGEN = "."; then
       DIR_ORIGEN=$CURRDIR

       if [ $SOURCE_BASENAME = "." ]; then

            aux_dir=$DIR_ORIGEN
            my_dirname $aux_dir
            DIR_ORIGEN=$RET_my_dirname

            my_basename $aux_dir
            SOURCE_BASENAME=$RET_my_basename

            debug "-- $RET_my_dirname - $RET_my_basename"

       fi     

       if [ $save_plain -eq 1 ]; then
         DIR_ORIGEN="."
       fi

    elif test $DIR_ORIGEN = ".."; then
       cd ..
       DIR_ORIGEN=`pwd`
       cd $CURRDIR

       if [ $SOURCE_BASENAME = ".." ]; then

            aux_dir=$DIR_ORIGEN
            my_dirname $aux_dir
            DIR_ORIGEN=$RET_my_dirname

            my_basename $aux_dir
            SOURCE_BASENAME=$RET_my_basename
       fi     

    fi
    # ------------------------------------------

    if [ $save_inplace -eq 1 -o  $save_plain -eq 1 ]; then
        DEST_DIR=${DIR_BASE_BACKUP} 
    else
        DEST_DIR=${DIR_BASE_BACKUP}${DIR_ORIGEN} 
    fi

    debug "DEST_DIR: $DEST_DIR"

    ABS_SOURCE_PATHNAME=$DIR_ORIGEN"/"$SOURCE_BASENAME
 
    
    # init
    status=$STAT_CONTINUE
    my_status=$STAT_OK

    if [ ! -f $ABS_SOURCE_PATHNAME -a ! -d $ABS_SOURCE_PATHNAME ]; then 
       # target file doesn't exist
       echo "860 - $MSG_NOT_FOUND $ABS_SOURCE_PATHNAME"
       my_status=$STAT_KO
    fi
    
    if [ $my_status -eq $STAT_OK ]; then 
       status=$my_status

       if [ ! -d $DEST_DIR ]; then 
          debug "mkdir -m $RWXR_XR_X -p $DEST_DIR 2> /dev/null"
          mkdir -m $RWXR_XR_X -p $DEST_DIR 2> /dev/null
          status=$?
       fi
    fi

    if [ $status -eq $STAT_CONTINUE ];then
        # nothing to do
        x=x
 
    elif [ $status -eq $STAT_OK ];then
       make_copy $SOURCE_BASENAME $ABS_SOURCE_PATHNAME $DEST_DIR
       status=$?
       
       # para usar en debug como un contador 
       COUNT=$COUNT"+"

       if [ $status -eq $STAT_OK ];then
         if [ $log_h_written -eq $STAT_KO ]; then
            log_h_written=$STAT_OK
            put_log_header 
         fi

         if [ -f $arg ]; then
             ABS_SOURCE_PATHNAME=$DIR_ORIGEN"/"$SOURCE_BASENAME
             ls_2_log $ABS_SOURCE_PATHNAME
         else
            echo $MSG_DIR_LIST $ABS_SOURCE_PATHNAME >> $LISTA
            list_2_log $ABS_SOURCE_PATHNAME
         fi
       else

         # make_copy has failed
          MSG_AUX="$DIR_ORIGEN/$SOURCE_BASENAME: $MSG_NOT_FOUND"
          echo $MSG_AUX 
       fi
       
    else   
       MENSAJE="900 - $MSG_CANT_CREATE_DIR $DEST_DIR"
       echo $MENSAJE
       #echo $MENSAJE >> $LISTA
    fi
    done
    # >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
done

# end of saveit
