#!/bin/sh

set -e

# Create GTK/Gnome places bookmark for easy access.
add_gnome_place() {
    SERVER="$1"
    USER="$2"
    GROUP="$3"
    TITLE="$4"
    SMBPATH="$5"
    echo "$SMBPATH $TITLE" >> /home/$USER/.gtk-bookmarks
    chown $USER:$GROUP /home/$USER/.gtk-bookmarks
}

# Create XBEL/KDE/Dolphin places bookmark for easy access
# See http://en.wikipedia.org/wiki/XBEL
create_xbel_place() {
    SERVER="$1"
    USER="$2"
    GROUP="$3"
    TITLE="$4"
    SMBPATH="$5"
    mkdir -p /home/$USER/.local/share
    cat > /home/$USER/.local/share/user-places.xbel <<EOF
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE xbel>
<xbel xmlns:bookmark="http://www.freedesktop.org/standards/desktop-bookmarks" xmlns:mime="http://www.freedesktop.org/standards/shared-mime-info" xmlns:kdepriv="http://www.kde.org/kdepriv">
 <bookmark href="$SMBPATH">
  <title>$TITLE</title>
  <info>
   <metadata owner="http://freedesktop.org">
    <bookmark:icon name="folder-remote"/>
   </metadata>
   <metadata owner="http://www.kde.org">
    <ID>1276594357/0</ID>
   </metadata>
  </info>
 </bookmark>
</xbel>
EOF
    chown -R $USER:$GROUP /home/$USER/.local
}

# FIXME Would be nice if the same bookmark file could be used for both
# KDE and Gnome
case "$ORIGHOMEDIR" in
    /*/*/*)
	homepath="$(ldapsearch -LLL -x '(&(uid=$USER)(sambaHomePath=*))' sambaHomePath | awk '/sambaHomePath: / { print $2 }')"
	if [ "$homepath" ] ; then
	    SMBPATH=$(echo "smb:$homepath" | tr '\' /)
	    SERVER="$(echo $SMBPATH | cut -d/ -f3)"
	else
            # Extract FQDN from home directory path
            SERVER="$(getent hosts $(echo $ORIGHOMEDIR | cut -d/ -f3) | awk '{print $2}')"
	    SMBPATH="smb://$SERVER/$USER/"
	fi

        GROUP="$(id -ng $USER)"
        TITLE="Network home for user $USER on $SERVER via SMB"
        add_gnome_place "$SERVER" "$USER" "$GROUP" "$TITLE" "$SMBPATH"
        create_xbel_place "$SERVER" "$USER" "$GROUP" "$TITLE" "$SMBPATH"
        ;;
esac

# Make sure local user have privileges through PolicyKit and can sudo
#adduser $USER sudo
