
#!/bin/sh
# File	: bcketc
# By	: M. de Boer,030601
# Subject : A backup script to make backup of (a lot of) etc (config) file
# Mod(1.6),MdB,060218: BCKDIR added
#set -x

PGM="`basename $0`"
VERSION="1.6"
CONF="/etc/bcketc.conf"
TAR="$PGM.tgz"
TMP="/tmp/$PGM.$$"
DATI="`date +%y%m%d_%H%M%S`"
MAIL=0
MAILADDRESS="deboer14@planet.nl"
NEWCONF=0
ROOTDIR="/etc"
MTIME="-365"
BCKDIR="./" 

USAGE()
{
  echo "$PGM: [-?] | [-h] | [-m|--mail] | [-a|--address <address>] | [--newconf [--root <dir>] ]"
  echo "Options:"
  echo "  -?|-h|--help : Help output"
  echo "  -a|--address : mailAddressi <address>"
  echo "  -m|--mail    : Mail the tar-file"
  echo "  -V           : Version number"
  echo "  --bckdir     : Dir for tgz file (default=$BCKDIR)"
  echo "  --newconf    : New conf-file"
  echo "  --rootdir    : Root dir. for the find with --newconf"
  echo "  --mtime      : mtime for the find with --newconf"
  echo "  --daynr      : Day of the month will be added to tar-file"
}
#echo "$1"

while [ $# -ne 0 ]
do
  case "$1" in
    -h|-?|--help) 
      USAGE
      exit 1
      ;;
    -V)
      echo "$PGM: Version $VERSION"
      exit 3
      ;;
    -a|--address)
      MAILADDRESS="$2"
      shift 1
      ;;
    -m|--mail)
      MAIL=1
      ;;
    --newconf)
      NEWCONF=1
      ;;
    --rootdir)
      ROOTDIR="$2"
      shift 1
      ;;
    --bckdir)
      BCKDIR="$2"
      shift 1
      ;;
    --mtime)
      MTIME="-$2"
      shift 1
      ;;
    --daynr)
      DAYNR="`date +%d`"
      TAR="$PGM-$DAYNR.tgz"
      ;;
    *)
      echo "Option $1 not known."
      USAGE
      exit 1
      ;;
  esac
  shift 1
done

if [ $NEWCONF = 1 ]; then
  echo "Creating new $CONF ..."
  rm -f $CONF
  find $ROOTDIR -type f -name "*.org"|tee -a $CONF
  find $ROOTDIR -type f -name "*.org"|cut -d"." -f1|tee -a $CONF
  find $ROOTDIR -type f -name "*.org"|awk -F. '{print $1"."$2}'|tee -a $CONF
  find $ROOTDIR -type f -mtime $MTIME |tee -a $CONF
  sort -u < $CONF > $TMP
  echo "Checking ..."
  cat $TMP | while read LINE
  do
    if [ -f $LINE ]; then
      echo $LINE >> $CONF
    fi
  done
  rm -f $TMP
fi

echo "$0" >> $CONF
sort -u < $CONF > $TMP
mv $TMP $CONF

if [ ! -f $CONF ]; then
  echo "$CONF not found. Exiting ..."
  exit 2
fi

tar czf $BCKDIR/$TAR -T $CONF

echo "Listing ..."
tar tvzf $BCKDIR/$TAR

if [ $MAIL = 1 ]; then
  echo "Mailing to $MAILADDRESS ..."
  mail -s "$PGM $DATI" $MAILADDRESS < $BCKDIR/$TAR
fi


