#!/bin/bash
#v1.3

VOL="";
CONF="$HOME/.switch-eject.conf"

usage() {
  echo "Usage: $0 [-c] [-e]

  -c: 'clear volume data'
  -e: 'eject volume when finished'
  " 1>&2
  exit 1
}

check_args() {
  while getopts "ceh" o; do
      case "${o}" in
          c)
              c=1
              ;;
          e)
              e=1
              ;;
          h)
              usage
              ;;
          *)
              usage
              ;;
      esac
  done
  shift $((OPTIND-1))
  if [ ! -z "${c}" ]; then
    [ -f $CONF ] && rm $CONF 1>&2
    VOL=""
  fi
}


[ -f $CONF ] && source $CONF
check_args $*

if [ -z "$VOL" ] ; then
  echo "Please type your switch sdcard volume name (ex: switch_128):"
  read VOL
  ([ -z "$VOL" ] || [ ! -d "/Volumes/$VOL" ]) && echo "Wrong volume name or sdcard not present" && exit 1
  echo "VOL=\"/Volumes/${VOL}\"" > "${CONF}"
  VOL="/Volumes/${VOL}"
fi

[ ! -d "$VOL" ] && echo "Wrong volume name or sdcard not present" && exit 1

#ask for root pass for next comands
sudo echo "Cleaning up sdcard" || exit 1
# turn off indexing on the specified volume
sudo mdutil -i off "${VOL}" > /dev/null 2>&1
# erase indexing on the specified volume
sudo mdutil -E "${VOL}" 2> /dev/null | grep -i indexing
# remove the spotlight index directory on the specified volume
sudo mdutil -X "${VOL}"
# remove dot and dot underbar files recursively on the specified volume
dot_clean -ms "${VOL}" > /dev/null 2>&1
# remove file system events directory on the specified volume
[ -d "${VOL}/.fseventsd" ] && rm -rf "${VOL}/.fseventsd"
# applies correct flags for all directories except Nintendo (as it might mess up installation files)
for i in $(printf '%s\n' ${VOL}/** | grep -ivE "nintendo|emutendo"); do
  [ -d "${i}" ] && echo "Fixing ${i}" && sudo chflags -R arch "${i}" > /dev/null 2>&1
done
# ejects the sdcard if the flag is there
[ ! -z "${e}" ] && echo "Ejecting ${VOL}" && sudo umount ${VOL}
echo
echo "Done!!"
