#!/bin/sh

me="[S12userdata]"

printf "%s Enter.\\n" "${me}"

# Load ipmodule variables
. /opt/gira/share/devicestack/ipmodule-vars

if ! [ -d ${MP_USERDATA} ]
then
    printf "%s Mount point for userdata partition does not exist and can not be created due to read-only filesystem!\\n" "${me}"
    printf "%s Setting bootcounter for booted system to 3.\\n" "${me}"
    printf "3\\n" > ${EXTPARAM}/booted_boot_counter
    ${ENVIRONMENT_SYNC_SCRIPT}
    printf "%s Reboot due to fatal error!\\n" "${me}"
    ${REBOOT}
fi

case "$1" in
  start)
    printf "%s Checking if userdata is already mounted..." "${me}"
    if [ ! -f ${UD_MOUNTED_FILE} ]
    then
      printf "nope.\\n"
      printf "%s Checking userdata fs for errors..." "${me}"
      fsck.${USERDATA_FS_TYPE} -n ${UD_BLOCKDEV} > /dev/null
      # Exit codes > 1 mean errors exist
      if [ "$?" -gt 1 ]
      then
        printf "errors found.\\n"
        # Repairing might take a minute? Disable watchdog to be sure it doesn’t
        # trigger during repair.
        printf "%s Temporarily disabling watchdog...\\n" "${me}"
        KERNEL_VERSION=$(uname -r)
        # Reload watchdog kernel module with nowayout=0
        rmmod imx2_wdt
        insmod /lib/modules/${KERNEL_VERSION}/kernel/drivers/watchdog/imx2_wdt.ko nowayout=0
        printf "%s Attempting file system repair...\\n" "${me}"
        fsck.${USERDATA_FS_TYPE} -y ${UD_BLOCKDEV}
        if [ "$?" -gt 1 ]
        then
          printf "%s Repair failed!\\n" "${me}"
          printf "%s Userdata partition is broken beyond repair. Executing factory reset as last resort!\\n" "${me}"
          printf "enabled\\n" > ${FACTORY_RESET_FILE}
          printf "Rebooting NOW!\\n"
          ${REBOOT}
        else
          printf "%s Repair was successful!\\n" "${me}"
        fi
        printf "%s Re-enabling watchdog...\\n" "${me}"
        rmmod imx2_wdt
        insmod /lib/modules/${KERNEL_VERSION}/kernel/drivers/watchdog/imx2_wdt.ko nowayout=1
      else
        printf "no errors found.\\n"
      fi
      printf "%s Mounting userdata fs ... " "${me}"
      $MOUNT -t ${USERDATA_FS_TYPE} -o rw,suid,sync,noatime ${UD_BLOCKDEV} ${MP_USERDATA}
      if [ ! "$(cat /proc/mounts | grep ${MP_USERDATA})" = "" ]
      then
        printf "done!\\n"

        # The configuration reset can only happen if userdata is mounted, so we check here.
        CONFIGURATION_RESET_CONDITION=0
        printf "%s Reading configuration reset condition from temp file \"%s\"\\n" "${me}" "${CONFIGURATION_RESET_FILE}"
        if [ -f "${CONFIGURATION_RESET_FILE}" ]
        then
          CONFIGURATION_RESET_CONDITION=`cat ${CONFIGURATION_RESET_FILE} | tr -d '\040\011\012\015'`
          printf "%s Condition: %s\\n" "${me}" "${CONFIGURATION_RESET_CONDITION}"
        else
          printf "%s Condition temp file \"%s\" not found!\\n" "${me}" "${CONFIGURATION_RESET_FILE}"
        fi
        if [ "enabled" = "${CONFIGURATION_RESET_CONDITION}" ]
        then
          printf "%s Configuration reset override detected, executing configuration reset.\\n" "${me}"
          ${CONFIGURATION_RESET}
        else
          printf "%s No configuration reset override detected, skipping.\\n" "${me}"
        fi
        # Either way, delete the temp file afterwards..
        printf "%s Removing temp condition file...\\n" "${me}"
        rm -f "${CONFIGURATION_RESET_FILE}"

        printf "%s Updating mount info.\\n" "${me}"
        touch ${UD_MOUNTED_FILE}
        printf "%s Creating FWU directory.\\n" "${me}"
        mkdir -p ${UD_FWU_DIR}
        logger -t "${me} userdata.initd" -s "Creating directories..."
        mkdir -p /opt/userdata/devicestack
        mkdir -p /opt/userdata/knxstack

        # Check if a user named 'logic' exists on the system.
        # If so, it will run the LogicEngine and have restricted access to files.
        # The $LOGIC_DIR needs to be writable though. This will be ensured here.
        LOGIC_DIR="/opt/userdata/logicengine"
        LOGIC_USER="logic"
        if id ${LOGIC_USER} >/dev/null 2>&1
        then
          # If so, make sure the 'logicengine' directory belongs to 'logic',
          # so the LogicEngine can write nodes and its configuration.
          mkdir -p ${LOGIC_DIR}
          # Check if directory does not yet belong to the logic user
          if [ "$(ls -ld ${LOGIC_DIR} | awk '{print $3}')" != "${LOGIC_USER}" ]
          then
            printf "%s Setting ownership of %s to %s ...\\n" "${me}" "${LOGIC_DIR}" "${LOGIC_USER}"
            chown -R ${LOGIC_USER}:${LOGIC_USER} ${LOGIC_DIR}
          fi
        fi
      else
        printf "%s Failed!\\n" "${me}"
        printf "%s Executing factory reset.\\n" "${me}"
        ${FACTORY_RESET}
        printf "%s Rebooting NOW!\\n" "${me}"
        ${REBOOT}
      fi
    else
      printf "yes, skip mounting.\\n"
    fi
    ;;
  stop)
    printf "%s Checking if userdata is mounted..." "${me}"
    if [ -f ${UD_MOUNTED_FILE} ]
    then
      printf "yes.\\n"
      printf "%s Unmounting userdata fs..." "${me}"
      sync
      $UMOUNT ${MP_USERDATA}
      if [ "$(cat /proc/mounts | grep ${MP_USERDATA})" = "" ]
      then
        printf "done.\\n"
      else
        printf "failed.\\n"
      fi
    else
      printf "nope. Nothing to do.\\n"
    fi
    ;;
  *)
    printf "%s Usage: %s (start|stop)\\n" "${me}" "$0"
    exit 1
esac

printf "%s Exit.\\n" "${me}"

exit 0
