#!/bin/sh

if [ "$STARTUP" == "1" ]; then
  exit;
fi

# check whether nickel is running
[ "$(pidof nickel | wc -w)" != "0" ] && nickelisrunning=true || nickelisrunning=false

MODULE_LOADED=`lsmod | grep -c g_file_storage`
if [ $MODULE_LOADED -gt 0 ]; then
  if [ "$ACTION" == "remove" ]; then
    [ "$nickelisrunning" == "true" ] && echo sd $ACTION $DEVNAME >> /tmp/nickel-hardware-status
    ACTION=remove /usr/local/Kobo/udev/plug
    sleep 5
    exit
  fi
fi

DEV="/dev/mmcblk1p1"
MOUNTARGS="noatime,nodiratime,shortname=mixed,utf8"

if [ "$DEV" == "$DEVNAME" ]; then
  if [ "$ACTION" == "add" ]; then
    dosfsck -a -w $DEVNAME
    mount -r -t vfat -o $MOUNTARGS $DEVNAME /mnt/sd
    if [ $? != 0 ]; then
      [ "$nickelisrunning" == "true" ] && echo sd mount fail $DEVNAME >> /tmp/nickel-hardware-status &
    else
      [ "$nickelisrunning" == "true" ] && echo sd $ACTION $DEVNAME >> /tmp/nickel-hardware-status &
      [ -e "/mnt/sd/autoscript.sh" ] && sh /mnt/sd/autoscript.sh
    fi
  fi
fi

if [ "$ACTION" == "remove" ]; then
  [ "$nickelisrunning" == "true" ] && echo sd $ACTION $DEVNAME >> /tmp/nickel-hardware-status &
  umount -l /mnt/sd
  sync
fi
