#!/bin/sh

me="[S12userdata]"

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

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

case "$1" in
  start)
    printf "%s Checking userdata fs ... " "${me}"
    if [ ! -f ${UD_MOUNTED_FILE} ]
    then
      printf "done.\\n"
      printf "%s Mounting userdata fs ... " "${me}"
      $MOUNT -t ${USERDATA_FS_TYPE} -o rw,suid,sync ${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

      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 "skipped (already mounted).\\n"
    fi
    ;;
  stop)
    printf "%s Checking userdata fs ... " "${me}"
    if [ -f ${UD_MOUNTED_FILE} ]
    then
      printf "done.\\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 "skipped (not mounted).\\n"
    fi
    ;;
  *)
    printf "%s Usage: %s (start|stop)\\n" "${me}" "$0"
    exit 1
esac

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

exit 0
