#!/bin/bash

# source the profile to get proper proxy settings, bnc#(678888)
. /etc/profile.d/profile.sh

zyppercmd="/usr/bin/zypper"
zcmd="/bin/false"
syscfgfile="/etc/sysconfig/automatic_online_update"

if [ -x ${zyppercmd}  ]
then
    zcmd="${zyppercmd} --non-interactive --quiet patch"
else
    echo "zypper is not installed. Can not run online update."
    exit 1
fi


if [ -f ${syscfgfile} ]
then
    . ${syscfgfile}
fi


if [ ! "$AOU_ENABLE_CRONJOB" = "true" ]
then
    echo "Online Update is disabled in ${syscfgfile}. Will not run update."
    exit 0
fi



if [ "${AOU_SKIP_INTERACTIVE_PATCHES}" = "true"  ] ; then
    zcmd="$zcmd --skip-interactive"
else
    zcmd="$zcmd --with-interactive"
fi

if [ "${AOU_AUTO_AGREE_WITH_LICENSES}" = "true"  ] ; then
    zcmd="$zcmd --auto-agree-with-licenses"
fi

if [ "${AOU_INCLUDE_RECOMMENDS}" = "true"  ] ; then
    zcmd="$zcmd --recommends"
else
    zcmd="$zcmd --no-recommends"
fi


function runzypper {
    # run passed arguments
    "$@"
    local status=$?
    # the return code 103 indicates a succesful patch of the zypper package
    # other patches might stil be waiting
    if [ $status -eq 103 ]; then
        echo "The Zypper package was patched, rerunning update to apply remaining patches."
        # rerun passed zypper command and use new status as return value
        "$@"
        status=$?
    fi
    return $status
}

# trim whitespaces
AOU_PATCH_CATEGORIES=`echo $AOU_PATCH_CATEGORIES`
# run the update
if [ -z "$AOU_PATCH_CATEGORIES" ] ; then
  runzypper $zcmd
else
  # handle errors for multiple categories
  ret=0

  for cat in $AOU_PATCH_CATEGORIES ; do
    runzypper $zcmd --category "$cat" || ret=$?
  done

  exit $ret
fi
