#!/bin/bash
#
# patch 'Tausch' and 'Nextcloud' into dolphin's bookmarks
#
set -eu

file="${1:-$HOME/.local/share/user-places.xbel}"

[[ -e "$file" ]] || exit 0

if grep -q "Tausch\|Nextcloud" "$file" ; then
    echo "Your Dolphin seems to already contain 'Tausch' and/or 'Nextcloud'." | tee "$file.lmn"
    exit 0
fi

id="$(grep ID "$file" | sed -E "s|^.+ID>([[:digit:]]+)/([[:digit:]]+)</ID.+$|\1:\2|" \
	    | sort -n -t: -k2 | tail -1 )"

if id | grep -q teachers; then
  NETHOME=/srv/samba/schools/default-school/teachers/$USER
else
  NETHOME=(/srv/samba/schools/default-school/students/*/"$USER")
fi
[[ -d $NETHOME ]] || exit 0

IDENTITY="${id%%:*}"
NUM0="${id##*:}"
NUM1=$(( NUM0 + 1 ))
NUM2=$(( NUM0 + 2 ))
NUM3=$(( NUM0 + 3 ))

if [[ $HOME =~ ^/home/ ]]; then
  HOMEONSERVER="+ <bookmark href=\"file://$NETHOME\">
+  <title>Home@Server</title>
+  <info>
+   <metadata owner=\"http://freedesktop.org\">
+    <bookmark:icon name=\"user-home-symbolic\"/>
+   </metadata>
+   <metadata owner=\"http://www.kde.org\">
+    <ID>$IDENTITY/${NUM1}</ID>
+    <isSystemItem>true</isSystemItem>
+   </metadata>
+  </info>
+ </bookmark>"
else
  HOMEONSERVER=$'+\n+\n+\n+\n+\n+\n+\n+\n+\n+\n+\n+'
fi

patch="
--- a/$file
+++ b/$file
@@ -98,9 +98,45 @@
     <isSystemItem>true</isSystemItem>
    </metadata>
   </info>
  </bookmark>
$HOMEONSERVER
+ <bookmark href=\"file:///srv/samba/schools/default-school/share\">
+  <title>Tausch</title>
+  <info>
+   <metadata owner=\"http://freedesktop.org\">
+    <bookmark:icon name=\"folder-publicshare\"/>
+   </metadata>
+   <metadata owner=\"http://www.kde.org\">
+    <ID>$IDENTITY/${NUM2}</ID>
+    <isSystemItem>true</isSystemItem>
+   </metadata>
+  </info>
+ </bookmark>
+ <bookmark href=\"file:///lmn/media/$USER/nextcloud\">
+  <title>Nextcloud</title>
+  <info>
+   <metadata owner=\"http://freedesktop.org\">
+    <bookmark:icon name=\"folder-cloud\"/>
+   </metadata>
+   <metadata owner=\"http://www.kde.org\">
+    <ID>$IDENTITY/${NUM3}</ID>
+    <isSystemItem>true</isSystemItem>
+   </metadata>
+  </info>
+ </bookmark>
  <bookmark href=\"remote:/\">
   <title>Network</title>
   <info>
    <metadata owner=\"http://freedesktop.org\">
     <bookmark:icon name=\"folder-network\"/>
"

echo "$patch" | patch -z '.lmn' --fuzz=0 --backup "$file"
