#!/usr/bin/sudo /bin/bash

#to se ni dostopno, ker ne moremo racunati na core.pack
#. /home/ROULETTE/common.config #here is configuration of ROULETTE and FC5 locations

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


#read config
DEST_PATH=/var/IGP/packages   #`cat pack-config/out.dir`
CREATE_FOLDER_IN_PACKAGE=0 #`cat pack-config/create.folder.in.package`
MOUNT_POINT=/mnt/tmp1 #`cat pack-config/mount.point`
PACK_NAME=terminal_home #`cat pack-config/name` #PACK_NAME=${1%%/}
SOURCE_PATHS_ARRAY=() #(`cat pack-config/source.paths`)
#just init terminal_home no copy., uncomment for copy current files to new pack
#SOURCE_PATHS_ARRAY+=("/var/IGP/terminal_home") #(`cat pack-config/source.paths`)
PRE_COPY_COMMAND="" # `cat pack-config/pre.copy.command`
ADDITIONAL_PACK_KB=12000000 #12GB #`cat pack-config/additional.pack.size.kb`
REDUCED_PACK_KB=0 #`cat pack-config/reduced.pack.size.kb`
ENCRYPT_PACK=0 #`cat pack-config/encrypt.pack`
WIPE_DEVICE=0 #`cat pack-config/wipe.device`


initTerminalHome()
{
	TMP_DIR=`pwd`
	if [ $CREATE_FOLDER_IN_PACKAGE -gt 0 ]; then
        	mkdir -p $MOUNT_POINT"/"$PACK_NAME
		cd $MOUNT_POINT"/"$PACK_NAME
	else
		cd $MOUNT_POINT
	fi
	#rsync -a  --exclude=*.pack.size.kb $src $MOUNT_POINT
	mkdir FIRMWARE
	mkdir log
	mkdir temp
	ln -sf ./10.5.10.1 192.168.0.1;ln -sf ./10.5.10.2 192.168.0.2;ln -sf ./10.5.10.3 192.168.0.3;ln -sf ./10.5.10.4 192.168.0.4;
	ln -sf ./10.5.10.5 192.168.0.5;ln -sf ./10.5.10.6 192.168.0.6;ln -sf ./10.5.10.7 192.168.0.7;ln -sf ./10.5.10.8 192.168.0.8;ln -sf ./10.5.10.9 192.168.0.9;
	ln -sf ./10.5.10.10 192.168.0.10;ln -sf ./10.5.10.11 192.168.0.11;ln -sf ./10.5.10.12 192.168.0.12;ln -sf ./10.5.10.13 192.168.0.13;
	ln -sf ./10.5.10.14 192.168.0.14;ln -sf ./10.5.10.15 192.168.0.15;ln -sf ./10.5.10.16 192.168.0.16
	#premaknemo firmware iz instalacije v novi terminal home, to je samo ob prvem install-u
	mkdir -p ./10.5.10.1
	mv /var/IGP/terminal_home/FIRMWARE ./10.5.10.1/FIRMWARE
	cp -R /home/IGP/pack_install/var/IGP/terminal_home_content/* .
	cd $TMP_DIR
SUCCESS=1
return 0
}


#if [ ! -d pack-config ]; then
#        echo "Folder with configuration files is missing. Make folder pack-config in pwd."
#        exit 1
#fi
#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.rw
else
        IMAGE_FILE=$DEST_PATH/$PACK_NAME.pack.rw
fi

if [ -f $IMAGE_FILE ];then
if [[ "$@" != *"FORCE_YES"* ]]; then
	echo
	echo "Confirm the removal of all localy stored GM history and logs."
	echo "Continue only if SURE. If you say no, nothing will be deleted."
	echo
	echo "Start with total erase of variable data storage[yes,NO]?"
	read ans
	[[ -z $ans ]] && ans="no" #default
	if [ $ans != "yes" ] && [ $ans != "YES" ]; then
		echo "User aborted."
		exit 0
	fi
	echo "Confirm again[YES,no]?"
	read ans
	[[ -z $ans ]] && ans="yes" #default
	if [ $ans != "yes" ] && [ $ans != "YES" ]; then
		echo "User aborted."
		exit 0
	fi
fi
fi

#if already exists, make .update, so that next startup will be renamed to .pack
if [ -f $IMAGE_FILE ]; then
        IMAGE_FILE=$IMAGE_FILE.update
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
let SIZE_KB=$ADDITIONAL_PACK_KB-$REDUCED_PACK_KB #if empty SOURCE_PATHS_ARRAY, we have to set here
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?
# ---VOID---
ENCRYPTED_PACK=$LOOPBACK_DEV
echo Package will not use encryption.

#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$
mkfs.ext4 -b 1024 $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


#INIT and COPY all paths to MOUNT_POINT
initTerminalHome
for src in "${SOURCE_PATHS_ARRAY[@]}"
do
        src=${src//\"}
        if [ $CREATE_FOLDER_IN_PACKAGE -gt 0 ]; then
                mkdir -p $MOUNT_POINT"/"$PACK_NAME
                rsync -a  --exclude=*.pack.size.kb $src $MOUNT_POINT"/"$PACK_NAME
        else
                rsync -a  --exclude=*.pack.size.kb $src $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

#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

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


