#!/bin/bash
#

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

common="/usr/lib/extended-you/common.sh"
[ -f ${common} ] && .  ${common}
[ -f ${notificationhelpers} ] && . ${notificationhelpers}

# helper to handle a needed restart of zypper
runzypper() {
  "$@"
  local status=$?

  if [ "$status" = "$ZYPPER_EXIT_INF_RESTART_NEEDED" ];
  then
    echo "The Zypper package was patched, rerunning update to apply remaining patches." >&2
    runzypper $@
  fi

  return $status
}

build_common_params() {
  local params=""

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

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

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

  echo $params
}

run_update() {
  local zcmd="${zyppercmd} --xmlout --non-interactive --quiet"
  local params=$(build_common_params)
  local zypperstatus=255

  if [ $1 = "patch" ];
  then
    zcmd="${zcmd} patch $params"

    # trim whitespaces
    AOU_PATCH_CATEGORIES=$(echo $AOU_PATCH_CATEGORIES)
    # run the update
    if [ -z "$AOU_PATCH_CATEGORIES" ];
    then
      runzypper $zcmd > "${tmp_dir}/patch.xml"
      zypperstatus=$?
    else
      for cat in $AOU_PATCH_CATEGORIES ; do
        runzypper $zcmd --category "$cat" > "${tmp_dir}/patch_${cat}.xml"
        zypperstatus=$?
      done
    fi
  else
    zcmd="${zcmd} update $params"

    runzypper $zcmd > "${tmp_dir}/update.xml"
    zypperstatus=$?
  fi

  return $zypperstatus
}


###############################################################################
#
# Main 
#

# only dump mail and do not delete temporary files
dry_run="true"

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

# exit codes of zypper
patchstatus=255
updatestatus=255

# 1. Patch system
run_update patch
patchstatus=$?

# 2. Update other packages if configured
if [ "$AOU_UPDATE_PACKAGES" = "true" ];
then
  run_update update
  updatestatus=$?
fi

# 3. Create notification if configured
if [ "$AOU_MAIL_ENABLE_UPDATESUMMARY" = "true" ];
then
  build_mail $patchstatus $updatestatus

  cat ${tmp_mail}
  sendmail -t < ${tmp_mail}
fi

# 4. Cleanup
rm -rf "$tmp_dir"
