#!/bin/sh

set -o errexit
set -o xtrace

FWU_STATUS_FILE="/opt/userdata/.fwu-status"
OFFLINE_SYSTEM_DIR="/opt/fwu/system_offline"

echo -n "started" > ${FWU_STATUS_FILE}

### BEGIN PRE SCRIPT COMMANDS ###

# Determining which system to overwrite
booted_system=$(fw_printenv -n bootsystem || true)
if [ "${booted_system}" = "A" ]
then
  echo "System A is booted. Overwriting system B."
  mmcpart=3
elif [ "${booted_system}" = "B" ]
then
  echo "System B is booted. Overwriting system A."
  mmcpart=2
elif [ -z "${booted_system}" ]
then
  echo "'bootsystem' not defined, probably commissioning. Assuming system A is booted."
  mmcpart=3
else
  echo "Failed to detect which system is booted."
  exit 1
fi

# Downgrades from unified packages dont't clean up the platform variable.
# So we clean it up here to not trigger unexpected behaviour. Major version 3 is
# currently the only one where the value 'android' would make sense.
MAJOR_VERSION=$(/opt/gira/bin/devicestack -cfv | cut -d '.' -f 1)
if ! [ "3" = "${MAJOR_VERSION}" ]
then
  fw_setenv platform linux
fi

# On Android, we can't mount anything below /opt/userdata, which is itself a mountpoint.
# To avoid this, we just provide symlinks to working mountpoints outside.
booted_platform=$(fw_printenv -n platform || true)
if [ "${booted_platform}" = "android" ]
then
  set +o errexit
  # rmdir will fail if those are missing or symlinks already
  rmdir /opt/userdata/fwu/system_offline /opt/userdata/fwu/system_current
  # Those might already exist
  ln -s /mnt/system_offline /opt/userdata/fwu/
  ln -s /mnt/system_current /opt/userdata/fwu/
  # There are situations where these directories are missing
  if ! [ -d /mnt/system_current ] || ! [ -d /mnt/system_offline ]
  then
    if touch /mnt > /dev/null 2>&1
    then
      mkdir -p /mnt/system_current
      mkdir -p /mnt/system_offline
    else # /mnt is not writeable, pre-script execution will fail
      echo "Failed to create required mountpoints. Abort!"
      exit 1
    fi
  fi
  set -o errexit
fi

# Preparing offline system for writing
mmcblkdev=/dev/mmcblk0
mkfs.ext3 -F ${mmcblkdev}p${mmcpart}
mkdir -p ${OFFLINE_SYSTEM_DIR}
mount -t ext3 -o noatime ${mmcblkdev}p${mmcpart} ${OFFLINE_SYSTEM_DIR}

echo "Preparing symlinks..."
tar xf rfs_regular_symlinks.tar -C ${OFFLINE_SYSTEM_DIR}

echo "Preparing directories..."
# TODO: This will print some non-critical error messages.
# 	The tar will try to create directories, which already have been created
#	by the symlink archive (for symlinks that are in subdirectories).
#	These will not cause the update to fail though.
tar xf rfs_regular_directories.tar -C ${OFFLINE_SYSTEM_DIR}
# The extracting and repacking in the build omits the ownership, which is
# required for sshd to work
chown root:root ${OFFLINE_SYSTEM_DIR}/gira/var/empty

### END PRE SCRIPT COMMANDS ###

echo -n "stopped" > ${FWU_STATUS_FILE}
echo "The pre-script has successfully done its job."
exit 0
