#!/bin/sh

# Compatibility layer for HDS Gen 1 updates
# Author: Reuben Dowle

# This provides an nfs mount point at /usr/share/navico/composer/updates, the
# location which HDS Gen 1 devices search for network updates. This is done by
# watching /media/, and when the first SD is inserted, it will export that.
# Only first SD card will be exported. Others are ignored

MEDIA_DIR=/media
EXPORT_DIR=/usr/share/navico/composer/updates
EXPORT_OPTIONS="-o no_subtree_check,no_root_squash"
INOTIFY_CMD="/sbin/inotifyd /bin/echo ${MEDIA_DIR}"
TEMP_FILE=/var/run/hdscompatshare.tmp
IGNORE="/media/factorydata"

remove_share() {
  /usr/sbin/exportfs -u *:${EXPORT_DIR}
  if /bin/grep -q "${EXPORT_DIR}" /proc/mounts; then
    /bin/umount ${EXPORT_DIR}
  fi
  /bin/rm -f "${TEMP_FILE}"
}

create_share() {
  # Not sure why, but sometimes the creation event occurs, but the bind mount
  # will fail unless there is some delay
  /bin/sleep 0.5
  if /bin/mount --bind $1 ${EXPORT_DIR}; then
    /bin/sleep 0.5
    if /usr/sbin/exportfs ${EXPORT_OPTIONS} *:${EXPORT_DIR}; then
      echo $1 > ${TEMP_FILE}
    else
      /bin/umount ${EXPORT_DIR}
    fi
  fi
}

# Make sure we remove any already existing share
remove_share

# Check if there is already an SD card inserted
for f in /media/* ; do
  if /bin/mountpoint -q "$f"; then
    if [ "$f" != "$IGNORE" ]; then
      create_share $f
      break
    fi
  fi
done

${INOTIFY_CMD} | while read EVENT DIR FILE; do
  PATH="${DIR}/${FILE}"
  case $EVENT in
    # Create a new share if a directory is create and are not currently sharing anything
    n) [ -d ${PATH} ] && ! [ -e ${TEMP_FILE} ] && create_share ${PATH}
       ;;
    # Remove the share if this path is one listed in the temp file as currently shared
    d) /bin/grep -q "${PATH}" "${TEMP_FILE}" && remove_share
       ;;
  esac
done
