#!/bin/sh
mount_data_partition()
{
	if ! mount /dev/mmcblk0p4 /mnt/data; then
		echo "Warning cannot mount data partition, using shadow partition"
		export QIBA_UCI_DEVICE="/mnt/shadow"
		if ! mount -o remount,rw /mnt/shadow/ ; then
			echo "Warning cannot mount the shadow area read-write !"
			return 1
		fi
	else
		echo "Existing partion /dev/mmcblk0p4 mounted on /mnt/data" 
		export QIBA_UCI_DEVICE="/mnt/data"
	fi
}
create_data_partition()
{
	newstart=$(($(cat /sys/block/mmcblk0/mmcblk0p3/start)+$(cat /sys/block/mmcblk0/mmcblk0p3/size)))
	newend=$(($(cat /sys/block/mmcblk0/size)-8))
	if [ "$newend" -gt "$newstart" ]
	then
		echo "Found extra space on SD card creating data partition"
		if ! parted -s /dev/mmcblk0 unit s mkpart primary ext2 $newstart $newend
		then
			echo "Cannot create new data partion"
			return 1
		fi
		echo "Formatting data partition ..."
		if ! mkfs.ext4 -F -i 4096 /dev/mmcblk0p4 >/dev/null
		then
			error_exit "cannot format data partition"
			return 1
		fi
		echo "Mounintg new data partition"
		mount_data_partition
	else
		echo "No space found for a new data partion, using shadow partition"
		export QIBA_UCI_DEVICE="/mnt/shadow"
		if ! mount -o remount,rw /mnt/shadow/ ; then
			echo "Warning cannot mount the shadow area read-write !"
			return 1
		fi
	fi
}
redo_data_partition()
{
	datastart=$(cat /sys/block/mmcblk0/mmcblk0p4/start)
	dataend=$(($(cat /sys/block/mmcblk0/size)-8))

	echo "Removing existing data partion"
    	if ! parted /dev/mmcblk0 rm 4
    	then
		echo "Cannot remove old data partion, aborting"
		return 1
	fi
	echo "Creating data partion with remaining space on SD card"
	if ! parted -s /dev/mmcblk0 unit s mkpart primary ext2 $datastart $dataend
	then
		echo "Cannot create bigger data partion, aborting..."
		return 1	
	fi
	echo "Formatting data partition ..."
	if ! mkfs.ext4 -F -i 4096 /dev/mmcblk0p4 >/dev/null
	then
		error_exit "cannot format data partition"
		return 1
	fi
}
check_data_partition()
{

	start=$(cat /sys/block/mmcblk0/mmcblk0p4/start)
	end=$(($start+$(cat /sys/block/mmcblk0/mmcblk0p4/size)))
	newend=$(($(cat /sys/block/mmcblk0/size)-8))

	if [ "$newend" -gt "$end" ]
	then
		echo "Found extra space on SD card expanding data partition"
		if umount /mnt/data; then
			echo "Removing existing data partion"
		    	if ! parted /dev/mmcblk0 rm 4
		    	then
				echo "Cannot remove old data partion, aborting"
				mount_data_partition
			fi
			echo "Creating data partion with remaining space on SD card"
			if ! parted -s /dev/mmcblk0 unit s mkpart primary ext2 $start $newend
			then
				echo "Cannot create bigger data partion, aborting..."
				mount_data_partition	
			fi
			echo "Resizing file system on data partition"
			if ! resize2fs -f /dev/mmcblk0p4
			then
				echo "Expanding /dev/mmcblk0p4 failed."
			fi
			echo "Mounting new data partition"
			mount_data_partition
		else
			echo "umount /dev/mmcblk0p4 failed, aborting partion expand."
		fi
	else
		echo "Existing data partion already uses all the SD card"
	fi
}

function set_password_with_path()
{
  # note: realm must match the one set in /etc/config.d/httpd
  realm="Barix Login"
  pwd_from_shadow=`jq -r .applicationPassword /mnt/shadow/config.json`
  hash_admin=`echo -n "admin:$realm:$pwd_from_shadow" | md5sum | cut -b -32`
  hash_user=`echo -n "user:$realm:user" | md5sum | cut -b -32`

  # get directory of input full file name
  SRC=$1
  BASE=${SRC##*/} 
  DIR=${SRC%$BASE}  

  rm -f $1
  mkdir -p $DIR 
  echo "admin:$realm:${hash_admin}" >> $1
  echo "user:$realm:${hash_user}" >> $1
}

echo "Setting up configuration ..."

if ! grep -qs /mnt/data /proc/mounts; then
  if ! ls /dev/mmcblk0p4
  then
  	echo "Cannot find SD card data partition ..."
  	create_data_partition
  else
	echo "Data partition did not mount properly, reformatting it over an existing one ..."
	redo_data_partition
	mount_data_partition
  fi	
else
  export QIBA_UCI_DEVICE="/mnt/data"
  check_data_partition
fi

if [ ! -d $QIBA_UCI_DEVICE/local ]; then
  mkdir $QIBA_UCI_DEVICE/local
fi

if [ ! -d /barix/local ]; then
  ln -sf $QIBA_UCI_DEVICE/local/ /barix/local
fi

if [ ! -d /barix/local/etc ]; then
    mkdir /barix/local/etc
fi

 # check to verify if a different Barix image is running
if [ -d /barix/local/config ] && [ -s /barix/local/qiba-version ]; then
  QIBA_CUR_VERSION=`cat /etc/qiba-version`
  QIBA_CUR_VERSION=${QIBA_CUR_VERSION:0:-15}
  QIBA_SET_VERSION=`cat /barix/local/qiba-version`
  QIBA_SET_VERSION=${QIBA_SET_VERSION:0:-15}
  if [ ${QIBA_CUR_VERSION} != ${QIBA_SET_VERSION} ] ; then
    echo "Different Barix image detected, removing settings ..."
    rm -rf /barix/local/config
  fi
fi

 # check to verify if default configuration needs to be installed
if [ ! -d /barix/local/config ]; then
	echo "Barix local config does not exist..."	
  mkdir -p /barix/local/config
  if [ -d /barix/config/defaults ]; then
    echo "Copying default Barix configuration ..."
    cp -r /barix/config/defaults/* /barix/local/config/
    cp -r /barix/config/etc/* /barix/local/etc/ 2>/dev/null || :
    cp /etc/qiba-version /barix/local
    if [ ! -f /barix/local/etc/passwd.hash ]; then
      if [ -f /mnt/shadow/config.json ]; then
        set_password_with_path /barix/local/etc/passwd.hash 2>&1 >/dev/null
      else
        mac2hash -f /barix/local/etc/passwd.hash 2>&1 >/dev/null
      fi
    fi
    if [ ! -f /barix/local/etc/.passwd ]; then
      if [ -f /mnt/shadow/config.json ]; then
        set_password_with_path /barix/local/etc/.passwd 2>&1 >/dev/null
      else
        mac2hash -f /barix/local/etc/.passwd 2>&1 >/dev/null
      fi
    fi
    echo "Syncing ..."
    sync
  else
    echo "Cannot find default Barix configuration ..."
  fi
else
	echo "Keeping existing local config ..."
fi

if [ ! -d /barix/local/app-data ]; then
  mkdir /barix/local/app-data
fi

echo "Configuration setup done."

exit 0
