#! /bin/bash
set -e

LIPSTICK_LABEL="LIPStick"
LIPSTICK_LABEL_ALT="$(echo -n "$LIPSTICK_LABEL" | tr "[a-z]" "[A-Z]")"

#find device
DEV="$(blkid -t "LABEL=$LIPSTICK_LABEL" -o device | head -n1 || echo '')"
if [ -z "$DEV" ]; then
  DEV="$(blkid -t "LABEL=$LIPSTICK_LABEL_ALT" -o device | head -n1 || echo '')"
fi

PS3="[1,2,3]<Enter>: "
while [ -z "$DEV" ];  do
  echo "Der LIP-Install-USB-Stick wurde nicht gefunden."
  echo "Jetzt einstecken oder ohne weitermachen"
  select i in "Stick ist jetzt gesteckt" \
"Ohne Stick weitermachen" \
"Installation abbrechen" ; do
    case $i in
     "Stick ist jetzt gesteckt")
       DEV="$(blkid -t "LABEL=$LIPSTICK_LABEL" -o device | head -n1 || echo '')"
       if [ -z "$DEV" ]; then
	 DEV="$(blkid -t "LABEL=$LIPSTICK_LABEL_ALT" -o device | head -n1 || echo '')"
       fi
       ;;
     "Ohne Stick weitermachen")
       DEV='-nomount-'
       ;;
     "Installation abbrechen")
       exit 2
       ;;
     *)
       echo "Das sollte nicht passieren. Helfer fragen."
       exit 99
       ;;
    esac
    break
  done
done

if [ "$DEV" = "-nomount-" ]; then
  echo "Mache ohne USB-Stick weiter."
  MPOINT=""
  #exit 0
else
  echo "Stick gefunden als $DEV"

  # ask udisks to mount it always.
  udisksctl mount --block-device "$DEV" || true

  # see where it is mounted
  DEVFILE=${DEV#/dev/}
#  MPOINT="$(dbus-send --print-reply=literal --system --dest=org.freedesktop.UDisks2 /org/freedesktop/UDisks2/block_devices/${DEVFILE} org.freedesktop.DBus.Properties.Get string:'org.freedesktop.UDisks2.Filesystem' string:'MountPoints' | tail -n +3 | tr -d "\ \]\[" | head -n 1 | xxd -r -p)"
MPOINT="$(udisksctl info --block-device "$DEV" | grep "MountPoints:" | tr -d ' ' | cut -d ':' -f2)"

  echo "Der Stick it als '$MPOINT' gemountet"
fi
#end;
