#!/bin/bash
# Create symlink in DocumentRoot/content to autmounted usb drive
#
# based on a similar script in the xs-rsync package
# by Martin Langhoff <martin@laptop.org>
#
# and the adaptation for xs-activity-server by Douglas Bagnall
# <douglas@paradise.net.nz>
#
# by Tim Moody tim@timmoody.com

source {{ iiab_env_file }}
case $IIAB_USB_LIB_SHOW_ALL in
'True'|'true'|'TRUE')
   logger -p user.notice -t "70-usb-library" -- "Display entire USB drive is True. Checking for rootfs or /library on $UM_MOUNTPOINT."
   # regularize the variable
   IIAB_USB_LIB_SHOW_ALL=True
   ;;
*)
   logger -p user.notice -t "70-usb-library" -- "Looking for /share, /Share, /Piratebox/Share, /USB, or /usb on $UM_MOUNTPOINT."
   ;;
esac

VERBOSE=yes

SHARE_DIR=""
# Only show content if in these directories

if [ -d $UM_MOUNTPOINT/share ]; then
  SHARE_DIR="$UM_MOUNTPOINT/share"
fi
if [ -d $UM_MOUNTPOINT/Share ]; then
  SHARE_DIR="$UM_MOUNTPOINT/Share"
fi
if [ -d $UM_MOUNTPOINT/Piratebox/Share ]; then
  SHARE_DIR="$UM_MOUNTPOINT/Piratebox/Share"
fi
if [ -d $UM_MOUNTPOINT/USB ]; then
  SHARE_DIR="$UM_MOUNTPOINT/USB"
fi
if [ -d $UM_MOUNTPOINT/usb ]; then
  SHARE_DIR="$UM_MOUNTPOINT/usb"
fi

if [ "$IIAB_USB_LIB_SHOW_ALL" == "True" ]; then
  UM_DEV=`findmnt $UM_MOUNTPOINT | grep / | awk '{print $2}'`
  LIB_DEV=`findmnt /library | grep / | awk '{print $2}' |awk -F '[' '{print $1}'`
  ROOT_DEV=`findmnt / | grep / | awk '{print $2}'`
  if [ "$UM_DEV" == "$LIB_DEV" ]; then
    logger -p user.notice -t "70-usb-library" -- "skipping $UM_MOUNTPOINT containing /library"
    #echo "lib on dev"
  elif [ "$UM_DEV" == "$ROOT_DEV" ]; then
    logger -p user.notice -t "70-usb-library" -- "skipping $UM_MOUNTPOINT containing rootfs"
    #echo "rootfs on dev"
  else
    SHARE_DIR="$UM_MOUNTPOINT"
  fi
fi

if [ ! -z "$SHARE_DIR" ]; then
  logger -p user.notice -t "70-usb-library" -- "Found Share Directory $SHARE_DIR."
else
  logger -p user.notice -t "70-usb-library" -- "did not find /share, /Share, /Piratebox/Share, /USB, or /usb on USB"
fi


if [ "$SHARE_DIR" != "" ];then
  CONTENT_LINK_USB=`basename $UM_MOUNTPOINT | awk '{print toupper($0)}'`
  CONTENT_LINK="{{ doc_root }}/local_content/$CONTENT_LINK_USB"
  logger -p user.notice -t "70-usb-library" -- "Creating link to $CONTENT_LINK."
  ln -s $SHARE_DIR $CONTENT_LINK
fi
