#!/bin/bash
#
#
# Relax & Recover
#
#    Relax & Recover 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 of the License, or
#    (at your option) any later version.

#    Relax & Recover 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 Relax & Recover; if not, write to the Free Software
#    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
#
# Authors: 
# Schlomo Schapiro <rear at schlomo.schapiro.org> [GSS]
# Gratien D'haese  <gdha at sourceforge.net> [GD]

# Versioning
PRODUCT="Relax & Recover"
VERSION="0.0.0"
RELEASE_DATE="2009-12-09"

COPYRIGHT="Copyright (C) 2006-2009
	Schlomo Schapiro
	Gratien D'haese, IT3 Consultants"
STARTTIME=$SECONDS

# Program directories - they must be set here. Everything else is then dynamic

SHARE_DIR="/usr/share/rear"
CONFIG_DIR="/etc/rear"
VAR_DIR="/var/lib/rear"
BUILD_DIR=/tmp/rear.$$
ROOTFS_DIR=$BUILD_DIR/rootfs
TMP_DIR=$BUILD_DIR/tmp


case $- in
	*i*) BATCHMODE=true  ;;
	  *) BATCHMODE=false ;;
esac

# make sure that we use only english
export LC_CTYPE=C LC_ALL=C LANG=C

# Calculate a unique build number by taking the md5sum over our script directories
BUILDNR="$(
		find $SHARE_DIR -type f -and -not -name \*~ |\
		while read ; do
			echo $REPLY
			cat "$REPLY"
		done | md5sum | cut -d " " -f 1
	)"

# Calculate a unique config build number
CONFIGBUILDNR="$(
	FILES=( $(find $CONFIG_DIR -type f -and -not -name \*~) ) ; ( echo ${FILES[@]} ; cat "${FILES[@]}" ) | md5sum | cut -d " " -f 1
	)"

# include default config
. $SHARE_DIR/conf/default.conf

# set the logfile for error logs
LOGFILE="/tmp/rear.log"
test -r "$LOGFILE" && mv -f "$LOGFILE" "$LOGFILE".old # keep old log file
exec 2>"$LOGFILE" || Error "Could not create $LOGFILE"

# include functions
for script in $SHARE_DIR/lib/*.sh ; do
	. $script
done

USAGE="$( basename "$0") [Options] <command> [command options ...]"'
'"$PRODUCT Version $VERSION / $RELEASE_DATE"'
Build: '"$BUILDNR"'
'"$COPYRIGHT"'
'"$PRODUCT"' comes with ABSOLUTELY NO WARRANTY; for details 
see the GNU General Public License at http://www.gnu.org/licenses/gpl.html

Available Options:
-V			version information
-d			debug mode
-D			debugscript mode
-S			Step-by-step mode
-s			Simulation mode (shows the scripts included)
-q			Quiet mode
-r a.b.c-xx-yy		kernel version to use (current: '"$KERNEL_VERSION"')

List of commands:
'"$(
for w in ${WORKFLOWS[@]} ; do
	description=WORKFLOW_${w}_DESCRIPTION
	test "${!description}" && printf "%-24s%s\n" $w "${!description}"
done
)"

test $# -eq 0 -o "${*//*--help*/--help}" == "--help" && Usage

STEPBYSTEP=
SIMULATE=
QUIET=

# Parse options
while getopts "VhdDSsqr:" Option
do
	case $Option in
	h ) Usage ;;
	V ) Print "$PRODUCT Version $VERSION / $RELEASE_DATE\nBuild: $BUILDNR\nConfig: $CONFIGBUILDNR\nLast changes:\n$(head -n 20 $SHARE_DIR/CHANGES)\n... See $SHARE_DIR/CHANGES for full list" ; exit 0 ;;
	v ) VERBOSE=1 ;;
	d ) DEBUG=1 ; VERBOSE=1 ; kill -PWR $ProgressPID ;;
	D ) DEBUGSCRIPTS=1 ;;
	s ) SIMULATE=1 ;;
	S ) STEPBYSTEP=1 ;;
	q ) QUIET=1 ;;
	r ) KERNEL_VERSION="$OPTARG" ;;
	* ) Error "Unknown Option $Option specified." ;;
	esac
done
shift $(($OPTIND - 1))
# Move argument pointer to next.

WORKFLOW=$1 ; shift # not "$1" to get rid of compound commands

ARGS=( "$@" )

test "$WORKFLOW" ||  Usage }

v=""
verbose=""
# Prepare stuff
if test "$VERBOSE" ; then
	v="-v"
	verbose="--verbose"
fi


LogPrint "$PRODUCT Version $VERSION / $RELEASE_DATE"
test "$SIMULATE" && LogPrint "Simulation mode activated, ReaR base directory: $SHARE_DIR"

shopt -s nullglob extglob

# All workflows need to read the configurations first.
# Combine configuration files
Log "Combining configuration files"
Source "$CONFIG_DIR/os.conf"	# use this file to manually override the OS detection
Source "$CONFIG_DIR/$WORKFLOW.conf"
SetOSVendorAndVersion
# distribution configuration files
for config in "$ARCH" "$OS" "$OS_VENDOR" "$OS_VENDOR_ARCH" "$OS_VENDOR_VERSION" "$OS_VENDOR_VERSION_ARCH" ; do
	Source $SHARE_DIR/conf/"$config".conf
done
# user configuration files
for config in site local ; do
	Source $CONFIG_DIR/"$config".conf
done


# change some options in debug mode
if test "$DEBUG"; then
	KEEP_BUILD_DIR=1
else
	KEEP_BUILD_DIR=
fi

# check for requirements
# are we root ?
if [ `id --user` -ne 0 ]; then
	Error  "$PRODUCT needs ROOT priviledges!"
fi
# do we have all required binaries ?
for f in "${REQUIRED_PROGS[@]}" ; do
	type -p "$f" >/dev/null|| Error "cannot find required program '$f'"
done

VERSION_INFO="
$PRODUCT Version $VERSION / $RELEASE_DATE
$(: Build: $BUILDNR)
$(: Config: $CONFIGBUILDNR)
$COPYRIGHT
$PRODUCT comes with ABSOLUTELY NO WARRANTY; for details
see the GNU General Public License at http://www.gnu.org/licenses/gpl.html

Host $(uname -n) using Backup $BACKUP and Output $OUTPUT
Build date: $(date -R)
"

# create build area
Log "Creating build area '$BUILD_DIR'"
mkdir -p -m 0700 $BUILD_DIR || Error "Could not create $BUILD_DIR"
mkdir -p $ROOTFS_DIR || Error "Could not create $ROOTFS_DIR"
mkdir -p $TMP_DIR || Error "Could not create $TMP_DIR"

# Check for and run the requested workflow
if type -t WORKFLOW_$WORKFLOW >/dev/null ; then
	Log "Running $WORKFLOW workflow"
	WORKFLOW_$WORKFLOW
	Log "Finished running $WORKFLOW workflow"
else
	LogPrint "ERROR: The specified command '$WORKFLOW' does not exist !"
	exit 10
fi

# Cleanup build area
echo "Finished in $((SECONDS-STARTTIME)) seconds."
if test "$KEEP_BUILD_DIR" ; then
	LogPrint "You should also rm -Rf $BUILD_DIR"
else
	Log "Removing build area $BUILD_DIR"
	rm -Rf $BUILD_DIR
fi
Log "End of program reached"
