#!/bin/bash

# Update fe packages

# Don't run when OEM
if [ "x${OEM}" = "x1" ]; then
    PACKAGES="omg-modules omg-utilities"
else
    PACKAGES="omg-utilities omg-modules omg-userfs"
fi


. /tmp/cmdline

if [ ! -z "${HTTP_PROXY}" ]; then
    export http_proxy=${HTTP_PROXY}
fi

let FULL=0
let REINSTALL=0

while getopts "frht:" opt;  do
    case "$opt" in
        
	f)  let FULL=1
	    ;;
        
	r)  let REINSTALL=1
	    ;;

	t)  FILENAME="$OPTARG"
	    ;;

	h)  echo "Usage: $0 [-f]"
	    echo "       update OfficeMasterGate"
	    echo "    -f full update"
	    echo "    -r reinstall"
	    echo "    -t update-tar-file"
	    echo "    -h gives this message"
	    exit 1;;
        
	*)
	    echo "See $0 -h for usage"
	    exit 1;;
    esac
done

# Sometimes it takes a long time ...
if [ -x /usr/bin/wdstop ] ; then
    /usr/bin/wdstop
fi

omgstop

# When called with an argument we have to perform an offline update
if [ ! -z "${FILENAME}" ] ; then
    echo "Performing offline update"
    if [ -e ${FILENAME} ] ; then
        if file -b ${FILENAME} | grep -q 'tar archive';then
            TMPDIR=$(mktemp -d)
            tar -C ${TMPDIR} -xf ${FILENAME}
            deblist=$(find ${TMPDIR} -name '*.deb')
            if [ -z "${deblist}" ] ; then
                echo "Error: Archive ${FILENAME} contains no packages"
                rm -rf ${TMPDIR}
                exit 1
            fi
            dpkg -i ${deblist}
            rm -rf ${TMPDIR}
            rm -f ${FILENAME}
            exit
        else
            echo "Error: This is not an archive"
            rm -rf ${TMPDIR}
            exit 1
        fi
    else
        echo "Error: File ${FILENAME} not found"
        exit 1
    fi
fi

apt-get clean

if ! $(file /bin/bunzip2|grep 'executable,' > /dev/null 2>&1) ; then
    # Kein programm
    echo "bunzip2 corrupt, trying to reinstall"
    apt-get install --reinstall bzip2
fi


if [ ${FULL} -eq 1 ] ; then
    if [ ${REINSTALL} -eq 1 ] ; then
        apt-get update
        apt-get -y install --reinstall ${PACKAGES}
    else
        apt-get -y update
        apt-get -y upgrade
    fi    
else
    if [ ${REINSTALL} -eq 1 ] ; then
        apt-get -o Dir::Etc::sourcelist=/etc/apt/fe-only.list update
        apt-get -y -o Dir::Etc::sourcelist=/etc/apt/fe-only.list install --reinstall ${PACKAGES}
    else
        apt-get -o Dir::Etc::sourcelist=/etc/apt/fe-only.list update
        apt-get -y -o Dir::Etc::sourcelist=/etc/apt/fe-only.list install ${PACKAGES}
    fi
fi


if [ ! -e /tmp/powercyle ]; then
    /usr/bin/omgstopilid
    /usr/bin/omgstartilid
    /etc/init.d/omg.setup
    /usr/bin/omgrestart
fi
sleep 30

