 #!/bin/bash

GREEN='\033[0;32m' #red
RED='\033[0;31m' #red
NC='\033[0m' # No Color
SUCCESS=0

PACK_CONF=$1
if [ ! -d $PACK_CONF ]; then 
	echo "Folder with configuration files is missing. Make folder pack-config in pwd."
	echo "Usage: pack-make.sh PACK_CONFIG_FOLDER"
	exit 1
fi
echo "*****Using pack configuration from $PACK_CONF**********"
#read config
DEST_PATH=`cat $PACK_CONF/out.dir`
CREATE_FOLDER_IN_PACKAGE=`cat $PACK_CONF/create.folder.in.package`
MOUNT_POINT=`cat $PACK_CONF/mount.point`
PACK_NAME=`cat $PACK_CONF/name`
#PACK_NAME=${1%%/}
SOURCE_PATHS_ARRAY=(`cat $PACK_CONF/source.paths`)
PRE_COPY_COMMAND=`cat $PACK_CONF/pre.copy.command`
ADDITIONAL_PACK_KB=`cat $PACK_CONF/additional.pack.size.kb`
REDUCED_PACK_KB=`cat $PACK_CONF/reduced.pack.size.kb`
ENCRYPT_PACK=`cat $PACK_CONF/encrypt.pack` 
WIPE_DEVICE=`cat $PACK_CONF/wipe.device` 
ENCRYPT_FILES_LIST=$(cat $PACK_CONF/encrypt.files)


if [ -z "$SOURCE_PATHS_ARRAY" ]; then
	echo "SPA $SOURCE_PATHS_ARRAY"
	echo "Nothing to copy to package. Please configure by setting pack-config/source.paths"
	exit 1
fi
if [ -z "$PACK_NAME" ]; then
	echo "Pack name is not defined. Please configure by setting pack-config/name"
	exit 1
fi

if [ -z "$ADDITIONAL_PACK_KB" ]; then
	ADDITIONAL_PACK_KB=0
fi
if [ -z "$REDUCED_PACK_KB" ]; then
	REDUCED_PACK_KB=0
fi
if [ -z "$ENCRYPT_PACK" ]; then
	ENCRYPT_PACK=0
fi
if [ -z "$CREATE_PACKAGE_FOLDER" ]; then
	CREATE_PACKAGE_FOLDER=0
fi
if [ -z "$WIPE_DEVICE" ]; then
	WIPE_DEVICE=0
fi

echo
for src in "${SOURCE_PATHS_ARRAY[@]}"
do
	if [ -d ${src//\*} ]; then
		echo "Package source: $src was not found."
		exit 1
	else
		echo "Package source: $src"
	fi
done
echo

#set destination pack name 
mkdir -p $DEST_PATH
if [ $ENCRYPT_PACK -gt 0 ]; then
	IMAGE_FILE=$DEST_PATH/$PACK_NAME.cpack
else
	IMAGE_FILE=$DEST_PATH/$PACK_NAME.pack
fi

echo "Compressing $PACK_NAME into $IMAGE_FILE. Please wait"

#moramo narediti INNER-ja predno izracunamo size za outer-ja!!!
#run pre-copy command - used to pack inner packs
if [ ! -z "$PRE_COPY_COMMAND" ]; then
	echo "Executing "$PRE_COPY_COMMAND
	/bin/bash -c "$PRE_COPY_COMMAND";
	if [ $? -ne 0 ]; then
		echo "ERROR with PRE_COPY_SCRIPT. Aborting..."
		exit 3
	fi
fi



#calculate the size of all sources for the package
SIZE_KB=0
for src in "${SOURCE_PATHS_ARRAY[@]}"
do 
	src=${src//\"}
	PATH_SIZE=`echo $(( \`du -c --block-size=1024 $src|tail -n1|cut -d't' -f1-1\` ))`
#echo $src" PATHSIZE raw ="$PATH_SIZE
	PATH_SIZE=`echo $(( ($PATH_SIZE*1053/1000)+300+$ADDITIONAL_PACK_KB-$REDUCED_PACK_KB))`
#echo $src" PATHSIZE corrected ="$PATH_SIZE
	SIZE_KB=$(($SIZE_KB + $PATH_SIZE))
done
echo -e "$YELLOW""Calulated Image size = $SIZE_KB""KB""$NC"
echo

#create image file
rm -rf $IMAGE_FILE
if [ $WIPE_DEVICE -ne 0 ]; then
	echo "Wiping was requested, using dd for "$IMAGE_FILE" of size "$SIZE_KB"kb."
       	dd if=/dev/zero of=$IMAGE_FILE bs=1024 count=$SIZE_KB
else
	echo "No wiping was requested, using falllocate for "$IMAGE_FILE" of size "$SIZE_KB"kb."
       	fallocate -l "$SIZE_KB"k $IMAGE_FILE
fi


#setup loopback device
losetup -fP $IMAGE_FILE
LOOPBACK_DEV=`losetup -a|grep $IMAGE_FILE|grep -v deleted|cut -d':' -f1-1`
echo Got LoopbackDevice $LOOPBACK_DEV

#do we use encription for the package?
if [ $ENCRYPT_PACK -gt 0 ]; then
	#open encryptedpack
	#cryptsetup open $LOOPBACK_DEV encryptedpack --type plain -c twofish <<< najdinasna15maj2b
	ENPACKNAME=`mktemp $PACK_CONF/encrypt_XXXX`
	ENPACKNAME=$(basename $ENPACKNAME)
	cryptsetup open $LOOPBACK_DEV $ENPACKNAME --type plain --hash sha256 --key-size=256 <<< najdinasna15maj2b
	ENCRYPTED_PACK=/dev/mapper/$ENPACKNAME
	echo We will encrypt this package.
else
	ENCRYPTED_PACK=$LOOPBACK_DEV
	echo Package will not use encryption.
fi

#create filesystem
echo
echo "Creating EXT4 filesystem for image $ENCRYPTED_PACK"
mkfs.ext4 -m0 -O ^has_journal -O ^resize_inode -O ^huge_file -O ^extra_isize -O ^metadata_csum -O ^dir_nlink -O ^ext_attr -b 2048 $ENCRYPTED_PACK > /dev/null 2>&1
tune2fs -l $ENCRYPTED_PACK|grep features

if [ ! -d $MOUNT_POINT ]; then
   MOUNT_POINT=`mktemp -d`
fi
if [ -z $MOUNT_POINT ]; then
   MOUNT_POINT=`mktemp -d`
fi

echo
echo Mounting image file $IMAGE_FILE on $MOUNT_POINT
mount -o loop $ENCRYPTED_PACK $MOUNT_POINT
if [ $? -ne 0 ]; then
	
	echo -e "$RED""ERROR mounting image file.""$NC"
	exit 2
fi
echo "Mounted. Copying..."

#######work with $MOUNT_POINT
rm -rf $MOUNT_POINT/lost+found


#TODO, kako to resit?
#kopiramo gor za run.sh, ce obstaja
#if [[ $PACK_NAME != *"Roulette"* ]]; then
#	if [ -f ./run.sh ]; then
#		rsync -a run.sh $PACK_NAME #update run.sh
#	fi
#fi

#COPY all paths to MOUNT_POINT
for src in "${SOURCE_PATHS_ARRAY[@]}"
do
	src=${src//\"}
	if [ $CREATE_FOLDER_IN_PACKAGE -gt 0 ]; then
		mkdir -p $MOUNT_POINT"/Game"
		rsync -a  --exclude=*.pack.size.kb --exclude=encrypt.files $src $MOUNT_POINT"/Game"
		chmod -R +r $MOUNT_POINT"/Game"
	else
		rsync -a  --exclude=*.pack.size.kb --exclude=encrypt.files $src $MOUNT_POINT
		chmod -R +r $MOUNT_POINT
	fi
	if [ $? -ne 0 ]; then
		echo -e "$RED$PACK_NAME: Error copying source files from '$src' to package, check package size.$NC"
		echo -e "$RED free space:"
		echo -e "Filesystem        Size     Used       Avail Use% Mounted on"
		df  |grep "$MOUNT_POINT"
		echo
		echo "Source size:"
		echo `du ./$PACK_NAME -h|tail -n 1`
		echo -e "$NC"
		SUCCESS=0
	else 
		SUCCESS=1
	fi
done

for File in $ENCRYPT_FILES_LIST
do
	DEST_FOLDER=$MOUNT_POINT
	if [ $CREATE_FOLDER_IN_PACKAGE -gt 0 ]; then
		DEST_FOLDER=$MOUNT_POINT"/Game"
	fi

	if [ -f $DEST_FOLDER/$File ]; then
		echo Encrypting file $File...
		openssl enc -aes-256-cbc -in $DEST_FOLDER/$File -out $DEST_FOLDER/$File.enc -k OutdatedVersion -pbkdf2 -iter 100000 -salt
		rm $DEST_FOLDER/$File
	fi
done

#add notice file in package
echo This file is to inform you that the content of this folder is a mounted package. > $MOUNT_POINT/THIS_IS_A_MOUNTED_PACKAGE

#show final size
if [ $SUCCESS -gt 0 ]; then
	echo -e "$GREEN""Filesystem        Size     Used       Avail Use% Mounted on"
	df |grep "$MOUNT_POINT"
	echo -e "$NC"
fi


#UMOUNT AND CLEANUP
echo "Done. Unmounting..."
umount $MOUNT_POINT
if [[ $MOUNT_POINT == *"/tmp/"* ]]; then #ce smo na temp, brisemo
	rmdir $MOUNT_POINT
fi
if [ $ENCRYPT_PACK -gt 0 ]; then
	echo "Unmounted. Closing cryptsetup..."
	sleep 1
	cryptsetup close $ENPACKNAME
fi

losetup -d $LOOPBACK_DEV

if [ $SUCCESS -gt 0 ]; then
	echo -e "$GREEN$PACK_NAME OK.$NC"
	echo
	exit 0
else
	echo -e "$RED$PACK_NAME failed.$NC"
	echo
	exit 1
fi
