#! /bin/bash
# multisession CDR backup utility
# by Junichi Uekawa
# 2001 Feb 14, the St. Valentine's day
# license: GPL version 2 or later

# defaults 
MKISOFS="sudo mkisofs"
CDRECORD="sudo cdrecord" 
DEVICE=0,1,0
SPEED=4

# load up local resource
for A in /etc/multisessioncdr.bash ~/.multisessioncdr.bash ; do
  if [ -e $A ] ; then
    . $A ;
  fi
done

if [ -z "$TMPDIR" ]; then
	TMPDIR=/tmp;
fi
ISOIMAGENAM=`tempfile -p cdriso -s .raw` || (
  echo "failed getting temporary filename"
  exit 1;
)

WORKDIR=$TMPDIR/$(date +%Y%m%d%H%M%S)
while [ -e $WORKDIR ]; do
  WORKDIR=x$WORKDIR 
done
mkdir $WORKDIR

# s= symlink only
# c= do a cp -a 
CPOPTION=s

# i= initialization
# a= append
# f= finalize
CDROPTION=a

BACKUPDIR=$WORKDIR/$(date +%Y%m%d%H%M%S)
mkdir $BACKUPDIR

if [ -z "$1" ]; then
  echo 'multisessioncdr.bash :  "-h" for help'
  exit 1 ; 
fi

while [ -n "$1" ]; do
  case "$1" in
    -s|--s*) CPOPTION=s ;; 
    -c|--c*) CPOPTION=c ;;
    -i|--i*) CDROPTION=i ;;
    -a|--a*) CDROPTION=a ;;
    -f|--f*) CDROPTION=f ;;
    -h|--h*) 
      cat <<EOF
multisessioncdr.bash : build CDR image which holds the directories specified.
  -s : use symlink 
      ( faster when building the image, but can't use symlinks inside)
  -c : use cp -a 
  -i : initialize CDR
  -a : append to CDR
  -f : finalize CDR
  -h : help
EOF
      exit 1
      ;;
    -*) echo "Unknwon option $1" ; exit ;; 
    *) 
      if [ "$CPOPTION" = "s" ]; then
        ln -s $(realpath "$1") $BACKUPDIR/ || (
          echo Error: file $1 does not exist
          exit 1
        )
      else 
        cp -a "$1" $BACKUPDIR/ || (
          echo Error: file $1 does not exist
          exit 1
        )
      fi
      echo $(realpath "$1") >> $BACKUPDIR/files.list
      ;; 
  esac
  shift;
done

echo CDR option is : $CDROPTION     CP option is : $CPOPTION
#find $WORKDIR
#ls -lR $WORKDIR

# copy or symlink mode
case $CPOPTION in
  c)
    MKISOFSOPT="-r -D -quiet"
  ;;
  s)
    MKISOFSOPT="-r -D -f -quiet"
  ;;
esac

case $CDROPTION in
  i)
    $MKISOFS $MKISOFSOPT -o "$ISOIMAGENAM" $WORKDIR && \
    $CDRECORD -v speed=$SPEED dev=$DEVICE -eject -multi "$ISOIMAGENAM"
  ;;
  a)
    $MKISOFS $MKISOFSOPT -M "$DEVICE" -C $($CDRECORD -msinfo dev=$DEVICE ) -o "$ISOIMAGENAM" $WORKDIR && \
    $CDRECORD -v speed=$SPEED dev=$DEVICE -eject -multi "$ISOIMAGENAM"
  ;;
  f)
    $MKISOFS $MKISOFSOPT -M "$DEVICE" -C $($CDRECORD -msinfo dev=$DEVICE ) -o "$ISOIMAGENAM" $WORKDIR && \ 
    $CDRECORD -v speed=$SPEED dev=$DEVICE -eject "$ISOIMAGENAM"
  ;;
esac


rm -r $WORKDIR
rm $ISOIMAGENAM
