#!/bin/sh
set -e

source /opt/fwu/ipmodule-functions

echo -n "started" > ${FWU_STATUS_FILE}

parse_arguments $1 $2 $3

MMC_DEV=/dev/mmcblk0
BL_UPDATE="bl.img"
BS_UPDATE="bs.img"
BL_VERSION="bl.ver"
BS_VERSION="bs.ver"
SET_ATTR="rfs_regular_setattr.sh"
SET_ATTR_EXTRA="extra_packages_setattr.sh"
BOOT_UPDATER="/opt/gira/bin/boot_updater"
CASE_SENSITIVE_LIBRARIES="${OFFLINE_SYSTEM_DIR}/usr/lib.tar"
CA_CERTIFICATES="${OFFLINE_SYSTEM_DIR}/usr/share/ca-certificates.tar"
TARPIPE_PRESCRIPT="tarpipe_postscript.sh"
TERMINFO_TAR="${OFFLINE_SYSTEM_DIR}/usr/share/terminfo.tar"
FILESYSTEM_TYPE=ext3

if [ -e "${TARPIPE_POSTSCRIPT}" ]
then
	echo "Executing tarpipe postscript."
	chmod +x "${TARPIPE_POSTSCRIPT}"
	"./${TARPIPE_POSTSCRIPT}"
fi

if [ -f "${CASE_SENSITIVE_LIBRARIES}" ]
then
	echo "[post-script] Extracting case sensitive libraries."
	pushd "${OFFLINE_SYSTEM_DIR}/usr"
	tar -xf ${CASE_SENSITIVE_LIBRARIES}
	rm -f ${CASE_SENSITIVE_LIBRARIES}
	popd
fi

if [ -f "${CA_CERTIFICATES}" ]
then
	echo "[post-script] Extracting ca-certificates."
	pushd "${OFFLINE_SYSTEM_DIR}/usr/share"
	tar -xf ${CA_CERTIFICATES}
	rm -f ${CA_CERTIFICATES}
	popd
fi

if [ -f "${TERMINFO_TAR}" ]
then
	echo "[post-script] Extracting terminfo.tar."
	pushd "${OFFLINE_SYSTEM_DIR}/usr/share"
	tar -xf ${TERMINFO_TAR}
	rm -f ${TERMINFO_TAR}
	popd
fi

echo "Preparing attribute script..."
[ -x ${SET_ATTR} ] || ${CHMOD} +x ${SET_ATTR}
cp ${SET_ATTR} ${OFFLINE_SYSTEM_DIR}

echo "Executing attribute script..."
# This *needs* to be executed inside a subshell for now, so it doesn't break from
# the 'set -e' flag. Some files given to 'chmod' in there do not exist.
(cd ${OFFLINE_SYSTEM_DIR} && ${SH} ${SET_ATTR} && rm -f ${SET_ATTR})

echo -n "Checking for extra attribute script ... "
if [ -e "${SET_ATTR_EXTRA}" ]
then
	echo "found."
	[ -x ${SET_ATTR_EXTRA} ] || ${CHMOD} +x ${SET_ATTR_EXTRA}
	mv ${SET_ATTR_EXTRA} ${OFFLINE_SYSTEM_DIR}
	echo "Executing extra attribute script..."
	(cd ${OFFLINE_SYSTEM_DIR} && ${SH} ${SET_ATTR_EXTRA} && rm -f ${SET_ATTR_EXTRA})
else
        echo "nothing found. Skipping."
fi

echo "Setting attributes for binaries..."
(${CHMOD} +x ${OFFLINE_SYSTEM_DIR}/opt/gira/bin/*)

umount /opt/fwu/system_offline

# Clean up extra_packages*.tar
rm -f extra_packages_*.tar

if [ "${COMMISSION}" != "TRUE" ]
then
	FIRMWARE_VERSION=`${DEVICESTACK} -cfv`
	cp ${DEVICECONFIG} ${DEVICECONFIG}.${FIRMWARE_VERSION}
	if [ -f ${DEVICECONFIG}.${FIRMWARE_VERSION} ]
	then
		echo "Created backup file: ${DEVICECONFIG}.${FIRMWARE_VERSION}"
	else
		echo "Failed to create backup file: ${DEVICECONFIG}.${FIRMWARE_VERSION}"
	fi
fi

if [ ! -f ${COMMISSIONED_FILE} ]
then
  echo "Disable commissioning mode..."
  echo "commissioned" > ${COMMISSIONED_FILE}
fi

if [ -e exchange-bootloader.sh ]
then
  chmod +x exchange-bootloader.sh
  ./exchange-bootloader.sh ${MMC_DEV} ${BL_UPDATE}
  return_code=$?
  if [ ! "${return_code}" = "0" ]
  then
    echo "exchange bootloader failed."
    exit 1
  fi
else
  echo "exchange-bootloader.sh not found"
  exit 1
fi


if [ -e /opt/extparam/boot.scr ]
then
  # if md5 file for boot script does not exist, create it.
  if ! [ -e /opt/extparam/boot.scr.md5 ]
  then
    (cd /opt/extparam && md5sum boot.scr > boot.scr.md5)
  fi

  installed_bootscript_md5=$(head -n 1 /opt/extparam/boot.scr.md5 | cut -d " " -f 1)
  contained_bootscript_md5=$(head -n 1 ./boot.scr.md5 | cut -d " " -f 1)

  echo "Installed U-Boot script hash is ${installed_bootscript_md5}"
  echo "Contained U-Boot script hash is ${contained_bootscript_md5}"

  # check if hashes differ and overwrite
  if ! [ "${installed_bootscript_md5}" == "${contained_bootscript_md5}" ]
  then
    echo "Overwriting U-Boot script now."
    cp ./boot.scr /opt/extparam/boot.scr
    cp ./boot.scr.md5 /opt/extparam/boot.scr.md5
  else
    echo "No need to overwrite U-Boot script."
  fi
else # Commissioning does not ship the bootscript.
  cp ./boot.scr /opt/extparam/boot.scr
  cp ./boot.scr.md5 /opt/extparam/boot.scr.md5
fi

sync
echo "Running file system check on offline system."
MMC_SYSTEM_OFFLINE=$(cat /opt/extparam/offline_root_blkdev)
fsck.${FILESYSTEM_TYPE} -y ${MMC_SYSTEM_OFFLINE}
EXIT_CODE=$?
if ! [ ${EXIT_CODE} -eq 0 ]
then
  echo "Filesystemcheck returned non-zero (code: |${EXIT_CODE}|). Stopping."
  exit 3
fi

# Check the current firmware version. If it is an old G1 1.x package,
# we want to trigger a factory reset for the reboot.
CURRENT_FW=$(cat /opt/extparam/booted_firmware_version)
# Get the major version number using 'cut'.
CURRENT_FW_MAJOR=$(echo "${CURRENT_FW}" | busybox cut -d. -f1)
if [ "${CURRENT_FW_MAJOR}" = "1" ]
then
  # Enable the factory reset
  echo -n enabled > /opt/extparam/factory_reset_condition
fi

# This 'stopped' within the FWU_STATUS_FILE is interpreted by the DeviceStack
# as "Everything is fine the Firmwareupdate completed successfully."
# So do not do anything below that shall mark the update as failure.
echo -n "stopped" > ${FWU_STATUS_FILE}
echo "The post-script has successfully done it's job and will now exit with return code 0."
exit 0
