#!/bin/bash

# check if we are started as root
# only one of UID and USER must be set correctly
if test "$UID" != 0 -a "$USER" != root; then
    echo "You must be root to start $0."
    exit 1
fi

umask 022

PREFIX="%PREFIX"
PROGDIR="%PROGDIR"
CHROME=$PROGDIR/chrome/installed-chrome.txt
CHROMEDIR=$PROGDIR/installed-chrome.d
LOCALES=$PROGDIR/chrome/locale.alias
LOCALEDIR=$PROGDIR/installed-chrome.d/locales

# disable usage of gconfd while registering
export MOZ_DISABLE_GCONF=1

# collect manually added chromes (if not called with argument --post)
if [ "$1" != "--post" ]; then
  if ! ( 2>/dev/null /bin/cat $CHROME | /usr/bin/sort | /usr/bin/uniq >$CHROME.uniq_file_tmp &&
      ( for i in $CHROMEDIR/* ; do [ "$i" = "$CHROMEDIR/manual" -o -d "$i" ] || /bin/cat "$i" ; done ) | /usr/bin/sort | /usr/bin/uniq >$CHROME.uniq_dir_tmp &&
      /bin/cat $CHROME.uniq_file_tmp $CHROME.uniq_dir_tmp | /usr/bin/sort | /usr/bin/uniq -u >$CHROMEDIR/manual )
  then
      echo "Collecting manually installed chromes failed."
  fi
  /bin/rm -f $CHROME.uniq_file_tmp $CHROME.uniq_dir_tmp
fi

# remove manually installed chromes
if [ "$1" = "--purge" ]
then
    if /usr/bin/sed <$CHROME -n 's%^.*,jar:resource:/*\([^!]*\).*/%\1%p' | /usr/bin/sort | /usr/bin/uniq >$CHROME.list_all_tmp &&
       /usr/bin/sed <$CHROMEDIR/manual -n 's%^.*,jar:resource:/*\([^!]*\).*/%\1%p' | /usr/bin/sort | /usr/bin/uniq >$CHROME.list_manual_tmp
    then
        echo "Removing all chromes not registered in $CHROMEDIR..."
        ( cd $PREFIX ; rm -vf $( /bin/cat $CHROME.list_all_tmp $CHROME.list_manual_tmp | /usr/bin/sort | /usr/bin/uniq -d ))
        echo -n "" >$CHROMEDIR/manual
        /bin/rm -f $CHROME.list_all_tmp $CHROME.list_manual_tmp $CHROME.list_old_tmp $CHROME.list_new_tmp
    else
        /bin/rm -f $CHROME.list_all_tmp $CHROME.list_manual_tmp $CHROME.list_old_tmp $CHROME.list_new_tmp
        echo "Chrome purge failed."
        exit 1
    fi
fi

# update installed chromes
rm -f $CHROME
for i in $CHROMEDIR/* ; do
  [ -r "$i" -a ! -d "$i" ] && /bin/cat "$i" >> $CHROME
done
/bin/rm -f $LOCALES
for i in $LOCALEDIR/* ; do
  [ -r "$i" -a ! -d "$i" ] && /bin/cat "$i" >> $LOCALES
done

# rebuild registries
if [ -f $PROGDIR/regxpcom ]; then

    export MOZILLA_FIVE_HOME=$PROGDIR
    export LD_LIBRARY_PATH=$MOZILLA_FIVE_HOME:$LD_LIBRARY_PATH

    /bin/rm -rf   $PROGDIR/chrome/overlayinfo
    /bin/rm -f    $PROGDIR/chrome/*.rdf
    /bin/mkdir -p $PROGDIR/chrome/overlayinfo
    /bin/rm -f    $PROGDIR/component.reg
    /bin/rm -f    $PROGDIR/components/compreg.dat

    $MOZILLA_FIVE_HOME/regxpcom >/dev/null 2>/dev/null
    $MOZILLA_FIVE_HOME/regchrome >/dev/null 2>/dev/null
fi

exit 0
