#!/bin/sh
#
# --------------------------------------------------------------------------
# Copyright notice
# --------------------------------------------------------------------------
# Copyright: Rene Mayrhofer, Mar. 2000
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2, or (at your option)
# 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 General Public License
# along with this program; see the file COPYING.  If not, write to
# the Free Software Foundation, 59 Temple Place - Suite 330,
# Boston, MA 02111-1307, USA.
# On Debian GNU/Linux systems, the complete text of the GNU General
# Public License can be found in `/usr/share/common-licenses/GPL'.
# --------------------------------------------------------------------------
#

# do not edit below this line
# =================================================

if [ $# -lt 2 ] ; then
  echo "Usage: $0 <mountpoint> <image name>"
  exit 1
fi

. /etc/default/common-definitions.sh

umask 077
set -e

image=$2
# strip the tailing '/' from the directory
if [ `expr $1 : '.*/$'` -gt 0 ]; then
  mountpoint=`expr $1 : '\(.*\)/$'`
else
  mountpoint=$1
fi
ramdev=`cat /proc/mounts | grep $mountpoint | cut -d' ' -f1,1`

# now check that the image is writable because otherwise proceeding would not
# make sense
if [ ! -w $image -a ! -w `dirname $image` ]; then
  echo "Error: $image can not be written !"
  exit 2
fi

# script hook for pre-save
call_script_hook pre-save $mountpoint $image $ramdev $runlev

try=1
success=0
while [ $success -ne 1 ] && [ $try -le $MAX_SAVE_TRIES ]; do
  echo -n "Saving $mountpoint to $image ... "
  pushd $mountpoint > /dev/null
  tar cz --preserve --same-owner --atime-preserve -f $image *
  echo "done"
  echo "Checking saved data for changes ... "
  if tar dz --preserve --same-owner --atime-preserve -f $image > /dev/null; then
    echo "successful"
    success=1
  else
    echo "unsaved changes detected - retrying."
  fi
  popd > /dev/null
  try=`expr $try + 1`
done

# script hook for post-save
call_script_hook post-save $mountpoint $image $ramdev $runlev

exit 0
