#!/bin/bash

help()
{
	echo "Help menu -- Save Config Script (${0})"
	echo "-----------------------------------"
	echo "-h / --help               - Shows help menu"
	echo "--output=[path]           - Path where to save the file, please use path without spaces"
	echo "-f                        - Include drivers in the config"
	echo "-p                        - Generate calpatch to restore easily (via sync&deploy or double-click)"
	echo "-----------------------------------"
	exit 0
}

# Base variables
DATE=$(date +%y%m%d-%H%M)
STARTDIRECTORY="$(dirname "$0")"

# Set variables to 0
CURRENTDIR=`pwd`
with_drivers=0
gen_calpatch=0
log_file=/tmp/save-config-$(date +%Y%m%d%H%M).log

echo "_10_" >> $log_file

# Parsing args
optspec=":fph-:"
while getopts "$optspec" optchar; do
    case "${optchar}" in
        -)
            case "${OPTARG}" in
                output=*)
                    val=${OPTARG#*=}
                    if [[ "$val" = /* ]];
					then
						OUTPUT="$val"
					else
						OUTPUT=`pwd`
						OUTPUT+="/$val"
					fi
                    ;;
				help)
					help
					;;
                *)
                    if [ "$OPTERR" = 1 ] && [ "${optspec:0:1}" != ":" ]; then
                        echo "Unknown option --${OPTARG}" >&2
                    fi
                    ;;
            esac;;
        f)
            with_drivers=1
            ;;
        p)
			gen_calpatch=1
            ;;
		h)
			help
			;;
        *)
            if [ "$OPTERR" != 1 ] || [ "${optspec:0:1}" = ":" ]; then
                echo "Non-option argument: '-${OPTARG}'"
            fi
            ;;
    esac
done

if [ -z "$OUTPUT" ]; then
	OUTPUT=${CURRENTDIR}/${DATE}_caldera_config
	if [ "$gen_calpatch" == 0 ]; then
		OUTPUT+=.tgz
	else
		OUTPUT+=.calpatch
	fi
fi

echo "_20_" >> $log_file

# More settings -----------------------------------------------------------------

case `uname` in
Linux)
	systemID=`lsb_release -is`
	;;
Darwin)
	systemID='Mac'
	;;
esac

ripVersion=`head -n 1 /opt/caldera/lib/CalderaVersion`
# For all Caldera Users
if [ "$systemID" == "Mac" ]
then
	if [ $ripVersion -lt 1300 ]
	then
		# For versions before v13, Users are only stored in /Users
		# We need the full path
		homedir=""
		HOMES='/CALDERADATA/Users/* /Users/*'
	else
		homedir=/Users
		HOMES=`ls /Users`
	fi
else
	homedir=/home
	HOMES=`ls /home/`
fi


configs="shared/ calserver.cfg"

excludes="--exclude=shared/InstalledDrivers"
excludes+=" --exclude=shared/IMAGES"
excludes+=" --exclude=shared/SKINS"

if [ $with_drivers -eq 1 ]
then
	configs+=" DRIVERS ICC_PROFILES"
	excludes+=" --exclude=ICC_PROFILES/DVLP"
	excludes+=" --exclude=DRIVERS/MISC"
fi

echo "_30_" >> $log_file

# Starting working -------------------------------------------------------------

WORKDIR="/tmp/.workdir"
SAVEDIR="$WORKDIR/$DATE"

if [ ! -d "$SAVEDIR" ]
then
	mkdir -p "$SAVEDIR"
fi

manifestFilename="$SAVEDIR/manifest.ini"
# Save the RIP version (usefull for restore script)
printf "[infos]\nrip_version=$ripVersion\n" > "$manifestFilename"
# Save the version of the archive (semver format)
printf "archive_version=2.0.0\n" >> "$manifestFilename"
users=""

printf "[home_origins]\n" >>$manifestFilename

for home in $HOMES
do
# printf "Using $home\n"
	if [ -d "$homedir/$home/.cas" ]
	then
		# $home: absolute path of the home directory
		# $user: basename of the home user directory
		user=`basename $home`
		# users+=" $user"
		# echo $users

		# Save homedir
		printf "$user=$homedir\n"
		printf "$user=$homedir\n" >> $manifestFilename

		# Create .cas tgz
		cd $homedir/$home
		printf "Backuping: "`pwd`"\n"
		tar -zcf $SAVEDIR/$user.tgz .cas/
		printf " $user" >> $SAVEDIR/users
	fi
done

# Global config
cd "/opt/caldera/lib/"



if [ -e "Bridge/config.cfg" ]
then
	configs+=" Bridge/config.cfg"
fi

tar $excludes -zcf $SAVEDIR/config.tgz $configs


echo "_60_" >> $log_file

# Add the list of drivers
drivers=`grep PRINTERNAME calserver.cfg | tr -s ' ' | cut -d' ' -f2`
for driver in $drivers
do
	echo $driver >> $SAVEDIR/drivers
done

cd $WORKDIR

echo "_80_" >> $log_file

if [[ "$gen_calpatch" = 1 ]];
then
	# Make a tarball then calpatch
	tar -zcf "$STARTDIRECTORY"/makepatch/Restore-Config/${DATE}_caldera_config.tgz $DATE/
	echo "_82_" >> $log_file
	bash "$STARTDIRECTORY"/makepatch/makepatch Restore-Config
	echo "_83_" >> $log_file
	rm -rf "$STARTDIRECTORY"/makepatch/Restore-Config/${DATE}_caldera_config.tgz
	echo "_84_" >> $log_file
	mv "$STARTDIRECTORY"/makepatch/Restore-Config.calpatch "$OUTPUT"
else
	# Make a global tarball
	tar -zcf "$OUTPUT" $DATE/
	echo "_85_" >> $log_file
fi


rm -fr $WORKDIR