#!/bin/sh

me="[$(printf $0 | xargs basename)]"

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 "${me} Checking if userdata is already mounted..."
    if [ ! -f "${UD_MOUNTED_FILE}" ]; then
      printf "nope.\\n"
      printf "${me} Checking userdata fs for errors..."
      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 "${me} Temporarily disabling watchdog...\\n"
        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 "${me} Attempting file system repair...\\n"
        fsck.${USERDATA_FS_TYPE} -y ${UD_BLOCKDEV}
        if [ "$?" -gt 1 ]; then
          printf "${me} Repair failed!\\n"
          printf "${me} Userdata partition is broken beyond repair. Executing factory reset as last resort!\\n"
          printf "enabled\\n" > ${FACTORY_RESET_FILE}
          printf "${me} Rebooting NOW!\\n"
          ${REBOOT}
        else
          printf "${me} Repair was successful!\\n"
        fi
        printf "${me} Re-enabling watchdog...\\n"
        rmmod imx2_wdt
        insmod /lib/modules/${KERNEL_VERSION}/kernel/drivers/watchdog/imx2_wdt.ko nowayout=1
      else
        printf "${me} no errors found.\\n"
      fi
      printf "${me} Mounting userdata fs ... "
      $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 "${me} Configuration reset override detected, executing configuration reset.\\n"
          ${CONFIGURATION_RESET}
        else
          printf "${me} No configuration reset override detected, skipping.\\n"
        fi
        # Either way, delete the temp file afterwards..
        printf "${me} Removing temp condition file...\\n"
        rm -f "${CONFIGURATION_RESET_FILE}"

        printf "${me} Updating mount info.\\n"
        touch ${UD_MOUNTED_FILE}
        printf "${me} Creating FWU directory.\\n"
        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_LOG_DIR="/var/log/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}
          mkdir -p ${LOGIC_DIR}/config && ln -sf /opt/gira/share/LogicEngine/log.config.xml ${LOGIC_DIR}/config/log.config.xml
          mkdir -p -m00755 ${LOGIC_LOG_DIR} && chown -R ${LOGIC_USER}:${LOGIC_USER} ${LOGIC_LOG_DIR}
          # Check if directory does not yet belong to the logic user
          if [ "$(ls -ld ${LOGIC_DIR} | awk '{print $3}')" != "${LOGIC_USER}" ]; then
            printf "${me} Setting ownership of ${LOGIC_DIR} to ${LOGIC_USER} ...\\n"
            chown -R ${LOGIC_USER}:${LOGIC_USER} ${LOGIC_DIR}
          fi
        fi
      else
        printf "${me} Failed!\\n"
        printf "${me} Executing factory reset.\\n"
        ${FACTORY_RESET}
        printf "${me} Rebooting NOW!\\n"
        ${REBOOT}
      fi
    else
      printf "yes, skip mounting.\\n"
    fi
    ;;
  stop)
    printf "${me} Checking if userdata is mounted... \\n"
    if [ ! -f "${UD_MOUNTED_FILE}" ]; then
      printf "${UD_MOUNTED_FILE} does not exist.\\n"
      exit 0    
    fi
    
    printf "${me} Unmounting userdata fs \\n"
    sync
    $UMOUNT ${MP_USERDATA}
    if [ "$(cat /proc/mounts | grep ${MP_USERDATA})" = "" ]; then
      printf "${me} Unmounting userdata fs done.\\n"
    else
      printf "${me} Unmounting userdata fs failed.\\n"
    fi
    ;;
  *)
    printf "%s Usage: %s (start|stop)\\n" "${me}" "$0"
    exit 1
esac

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

exit 0
