#!/bin/sh
#
# suse2debian.init v1.0 2012-01-31 GS
# (c) Goesta Smekal (goesta@smekal.at)
#
# suse2debian.init is part of suse2debian. See suse2debian.sh for terms and
# and conditions

# looks for usb-storage devices, mounts them and checks for presence of valid
# recordum backup file

### BEGIN INIT INFO
# Provides: suse2debian
# Required-Start: udev mountall-bootclean
# Required-Stop:
# Default-Start: S
# Default-Stop:
# Short-Description: suse2debian
# Description: Import backups from SuSE based system to new Debian system
### END INIT INFO

if [ -r /lib/lsb/init-functions ]
then
  . /lib/lsb/init-functions
else
  echo "suse2debian requires LSB 3.0 or later."
  exit 1
fi

MYPATH='/usr/local/recordum/suse2debian'
LOGPATH='/var/log/recordum'
IMPORTSCRIPT="$MYPATH/suse2debian.sh"

if [ ! -x $IMPORTSCRIPT ]
then
  log_failure_msg 'suse2debian import script missing or not executeable'
  exit 5
fi

MOUNTPOINT='/mnt/recordum_backup'
BACKUP='SUSE-system-backup.tar.gz'
TEMPDIR='/tmp/recordum_backup'
STATUSFILE="$MYPATH/suse2debian.done"

# look if our work has already been done ...
if [ -e $STATUSFILE ]
then
  STATUS=`tail -n 1 $STATUSFILE`
  if [ 'import done.' = "$STATUS" ]
  then
    # ... it has
    log_success_msg 'suse2debian import already done.'
    exit 0
  fi
fi

if [ ! "$1" = 'start' ]
then
  # nothing but 'start' is useful ...
  log_success_msg 'suse2debian has nothing to do'
  exit 0
fi

# prepare mountpoints and temporary workspace
if [ ! -d $MOUNTPOINT ]
then
  mkdir -p $MOUNTPOINT
fi
if [ ! -d $TEMPDIR ]
then
  mkdir -p $TEMPDIR
fi

ARCHIVE_FOUND='no'
# loop over partitions on usb storage devices
for DEVICE in `ls /dev/disk/by-path/ |grep usb |grep part`
do
  if mount /dev/disk/by-path/$DEVICE $MOUNTPOINT
  then
    if [ -r $MOUNTPOINT/$BACKUP ]
    then
      cd $TEMPDIR
      if ! tar xvf $MOUNTPOINT/$BACKUP
      then
        log_failure_msg "suse2debian extraction of archive failed: $!"
        umount $MOUNTPOINT
	rmdir $MOUNTPOINT
	exit 1
      else
        # extraction successful
        ARCHIVE_FOUND='yes'
      fi
    fi
    umount $MOUNTPOINT
  else
    echo "suse2debian failed to mount $DEVICE: $!"
  fi
done
rmdir $MOUNTPOINT

if [ "$ARCHIVE_FOUND" = 'no' ]
then
  log_success_msg 'suse2debian found no backup to restore'
  exit 0
fi

# now we have everything in place, start converter script ...
touch $STATUSFILE
if $IMPORTSCRIPT $TEMPDIR
then
  # mark work as done
  echo 'import done.' >> $STATUSFILE
  # dirty hack to set new network config
  ifdown eth0
  ifup eth0
  log_success_msg 'suse2debian import of config succeeded'
  exit 0
else
  log_failure_msg "import of suse config failed. check $LOGPATH/suse2debian.log"
  exit 1
fi
