#!/bin/sh
#(c) Robert Shingledecker 2004,2005,2006,2007
#
. /etc/init.d/dsl-functions

DESKTOP="$(getoption.lua $HOME/.desktop wm)"
DSLUSER="$(cat /etc/sysconfig/dsluser)"
MYDSLDIR="$(realpath `cat /opt/.mydsl_dir`)"
MAP="/tmp/mydsl.map"
SOURCE="$1"
BASE=`basename "$1"`
SHUTDOWN="$2"

stringinstring "cdrom2" "$SOURCE" && SOURCE="/mnt/auto/cdrom/optional/$BASE"

APP=$(getbasefile "$BASE" 1)
mount | grep "$BASE"
if [ "$?" == 0 ]; then
   [ ${BASE##*.} == "unc" ] && exit 1
   if [ -f "/opt/$APP/user.tar.gz" ]; then
      if [ -f /tmp/mydsl.menu/"$APP" ]; then
         rm /tmp/mydsl.menu/"$APP"
 
         for FILE in $(tar -ztf /opt/"$APP"/user.tar.gz); do
            rm -rf "/$FILE"
         done

         for FILE in $(cat /tmp/mydsl.installed/"$APP"); do
            rm -f "$MYDSLDIR"/"$FILE" 2>/dev/null
         done

         cp /opt/.mydsl_menu/"$DESKTOP"/menu_template /opt/.mydsl_menu/"$DESKTOP"/menu
         if [ -z "$SHUTDOWN" ]; then 
            for FILE in `ls /tmp/mydsl.menu`; do
               sudo -u "$DSLUSER" /usr/bin/desktop.sh "$FILE"
            done
            /opt/.mydsl_menu/"$DESKTOP"/restart 2>/dev/null
         fi
      fi
   fi

   sleep 1
   sudo umount "$SOURCE"
   if [ "$?" != 0 ]; then
      exit 1
   fi

   n=`sudo /etc/init.d/cloopmap.lua "$MAP" "$SOURCE" "free"`

   rm -rf "/opt/$APP"
   echo "$1" successfully unmounted!
   exit 0 
else
   if [ ! -d "/opt/$APP" ]; then
      mkdir "/opt/$APP"
   fi
   
   n=`/etc/init.d/cloopmap.lua "$MAP" "free" "$SOURCE"`
   mount "$SOURCE" "/opt/$APP" -t iso9660 -o ro,loop=/dev/cloop$n
   if [ "$?" != 0 ]; then
      if [ -n "$DISPLAY" ]; then
         popup.lua "Please mount media containing optional dir and try again."
      else
         echo -n "Please mount media containing optional dir and try again."
         read gagme
      fi
      n=`sudo /etc/init.d/cloopmap.lua "$MAP" "$SOURCE" "free"`
      exit 1
   fi

   if [ -f "/opt/$APP/user.tar.gz" ]; then
      sudo /etc/init.d/mydsl-install "/opt/$APP/user.tar.gz"
   fi
   if [ ${BASE##*.} == "unc" ]; then
      sudo /etc/init.d/unc add "$APP"
   fi

   # Add extra libraries into search path
   if [ ${BASE##*.} == "uci" ]; then
      for F in `find /opt/"$APP" -type f -name "*.so*"`; do dirname "$F"; done | sort | uniq >> /etc/ld.so.conf
      ldconfig 2>/dev/null
   fi

   sudo -u "$DSLUSER" /usr/bin/desktop.sh "$APP"

   echo "$SOURCE" sucessfully loaded!
   exit 0
fi
