#!/bin/bash
set -e
set -o pipefail

usage() {
    cat << EOF
Usage: openqa-auto-update
Trigger automatic system upgrade and reboot if devel:openQA packages are stable

Options:
 -h, --help         display this help
EOF
    exit "$1"
}

opts=$(getopt -o h --long help -n 'parse-options' -- "$@") || usage 1
eval set -- "$opts"
while true; do
  case "$1" in
    -h | --help ) usage 0; shift ;;
    -- ) shift; break ;;
    * ) break ;;
  esac
done

# shellcheck disable=SC1091 disable=SC2015
. /etc/os-release && result="$(curl -s "https://api.opensuse.org/public/build/devel:openQA/_result?repository=openSUSE_Leap_${VERSION}&arch=$(uname -i)")" && echo -e "$result" | grep -q "project.*state=.published." && echo "$result" | grep "status package" | (! grep -vE "(disabled|succeeded|excluded)") && zypper -n dup --replacefiles --auto-agree-with-licenses --force-resolution --download-in-advance && needs-restarting --reboothint >/dev/null || (command -v rebootmgrctl >/dev/null && rebootmgrctl reboot ||:)
