#!/usr/bin/bash
#
# Activate a module, while running LiveCD.

if [ "$1" = "-k" ]; then
   CALLED_BY_KDE_HELPER=1
   shift
fi

if [ -e /usr/bin/kactivate -a "$DISPLAY" -a ! "$CALLED_BY_KDE_HELPER" ]; then
   exec /usr/bin/kactivate "$@" 2>/dev/null
fi

MODULE=$(readlink -f "$1")

if [ "$MODULE" = "" -o ! -e "$MODULE" -o -d "$MODULE" ]; then
   echo
   echo "Activate a module on the fly while running Linux Live"
   echo "Usage: $0 module.[xzm|lzm|rwm|rom|enc]"
   exit 1
fi

if ! echo $MODULE | egrep -qi 'lzm|xzm|rom|enc' ;then
   echo 
   echo "$(basename $MODULE): Module must end with .xzm .lzm .rwm .rom .enc"
   exit 2
fi

PATH=.:$(dirname $0):/usr/lib:$PATH
. liblinuxlive || exit 3

allow_only_root
IMAGES=/mnt/live/memory/images
MODULES=/mnt/live/memory/modules

# are we even using union?
if [ "$(grep '^aufs / ' /proc/mounts)$(grep '^unionfs / ' /proc/mounts)" = "" ]; then
   echo "Not in the live mode, can't continue. Try lzm2dir $MODULE /"
   exit 4
fi

mkdir -p "$MODULES"

# Test whether the module file is stored in union
# if yes, then we must move it somewhere else (to RAM) else it can't be added
if [ -e "/mnt/live/memory/changes/$(readlink -f "$MODULE")" ]; then
   echo "Module file is stored inside the union, moving to $MODULES first..."
   TARGET="$MODULES/$(basename "$MODULE")"
   mv "$MODULE" "$TARGET"
   if [ $? -ne 0 ]; then
      echo "Error copying module to memory, not enough free RAM? Try df" >&2
      rm "$TARGET"
      exit 6
   fi
   MODULE="$TARGET"
fi
echo "$MODULE"
MOD=$(union_insert_module / "$MODULE" $IMAGES)
#echo $MOD
if [ $? -ne 0 ]; then echo "Error inserting module to live filesystem" >&2; exit 3; fi

# All executables (but symlinks) in /etc/rc.d/init.d/ from this module will be started
# with two arguments: "start" "activate".
# This is done only by the 'activate' script, not in the case when the module is loaded 
# during OS startup (in that case, your distro is responsible for execution)
#
# For compatibility, /etc/init.d is also examined, but it's not recommended for you to put your startup scripts
# there in your module

MOD="$IMAGES/$(basename $MOD)"

find_n_run_scripts $MOD start activate

# update ld cache if new ld.so.conf/cache exists in the module
if [ -e "$MOD/etc/ld.so.conf" -o -e "$MOD/etc/ld.so.cache" ]; then
   echo "Module contains ld.so.conf or ld.so.cache, updating libs cache..."
   /sbin/ldconfig
fi

# update menus and icons
if [ -e "$MOD/usr/share/applications" ]; then
   gtk-update-icon-cache -fit /usr/share/icons/hicolor
   ps -A | grep -q gam_server || killall -1 lxpanel mate-panel 2>/dev/null
   touch /usr/share/applications/screensavers
fi
