#!/bin/sh
set -e

source /opt/fwu/ipmodule-functions

printf "started" > ${FWU_STATUS_FILE}

parse_arguments $1 $2 $3

TAR_DIRS="rfs_regular_directories.tar"
TAR_SYMS="rfs_regular_symlinks.tar"
TAR_DEVS="rfs_regular_devices.tar"

EXTRA_DIRS="extra_packages_directories.tar"
EXTRA_SYMS="extra_packages_symlinks.tar"

FILESYSTEM_TYPE=ext3

if [ ! -d "/opt/fwu/system_offline" ]
then
  mkdir "/opt/fwu/system_offline"
fi

printf "Identifying offline system...\\n"
BOOTED_SYSTEM=$(cat /opt/extparam/booted_system)
printf "BOOTED_SYSTEM=%s\\n" "${BOOTED_SYSTEM}"

if [ "${BOOTED_SYSTEM}" != "A" ]
then
  if [ "${BOOTED_SYSTEM}" != "B" ]
  then
    if [ "${COMMISSION}" != "FALSE" ]
    then
      printf "Commissioning Mode -> Selecting System B as offline system.\\n"
      OFFLINE_SYSTEM=B
    else
      printf "FATAL: Failed to select booted system. BOOTED_SYSTEM=%s\\n" "${BOOTED_SYSTEM}"
      exit 9
    fi
  else
    printf "Update Mode -> Determined System A as offline system.\\n"
    OFFLINE_SYSTEM=A
  fi
else
  printf "Update Mode -> Determined System B as offline system.\\n"
  OFFLINE_SYSTEM=B
fi

SYSTEM_OFFLINE=$(cat /opt/extparam/system_${OFFLINE_SYSTEM}_root_blkdev)

# unmount if mounted
if [ "$(mount | grep ${SYSTEM_OFFLINE} | wc -l)" -gt "0" ]
then
  umount ${SYSTEM_OFFLINE}
  printf "umount done.\\n"
else
  printf "not mounted.\\n"
fi

# create new file system
mkfs.${FILESYSTEM_TYPE} -F ${SYSTEM_OFFLINE}

# mount it
mount -t ${FILESYSTEM_TYPE} ${SYSTEM_OFFLINE} -o noatime,nodiratime /opt/fwu/system_offline

printf "Preparing directories...\\n"
tar xf ${TAR_DIRS} -C ${OFFLINE_SYSTEM_DIR}

if [ -e "${EXTRA_DIRS}" ]
then
  tar xf ${EXTRA_DIRS} -C ${OFFLINE_SYSTEM_DIR}
  rm -f ${EXTRA_DIRS}
else
  printf "No extra packages, skipping.\\n"
fi

printf "Preparing symlinks...\\n"
tar xf ${TAR_SYMS} -C ${OFFLINE_SYSTEM_DIR}

if [ -e "${EXTRA_SYMS}" ]
then
  tar xf ${EXTRA_SYMS} -C ${OFFLINE_SYSTEM_DIR}
  rm -f ${EXTRA_SYMS}
else
  printf "No extra packages, skipping.\\n"
fi

printf "Preparing devices...\\n"
tar xf ${TAR_DEVS} -C ${OFFLINE_SYSTEM_DIR}/dev

printf "stopped" > ${FWU_STATUS_FILE}
printf "The pre-script has successfully done it's job and will now exit with return code 0.\\n"
exit 0
