#!/bin/bash
# -*- mode: sh; indent-tabs-mode: nil; sh-basic-offset: 4; -*-
# vim: et sts=4 sw=4

#  SPDX-License-Identifier: LGPL-2.1+
#
#  Copyright © 2019-2020 Collabora Ltd.
#  Copyright © 2019-2020 Valve Corporation.
#
#  This file is part of steamos-customizations.
#
#  steamos-customizations is free software; you can redistribute it and/or
#  modify it under the terms of the GNU Lesser General Public License as
#  published by the Free Software Foundation; either version 2.1 of the License,
#  or (at your option) any later version.

set -e
set -u

usage() {
    cat <<EOF
Usage: ${0##*/} now [ATOMUPD-OPTIONS]
       ${0##*/} after-reboot
       ${0##*/} -h|--help
EOF
}

update_now() {
    if ! steamos-atomupd-client "$@"; then
        echo "SteamOS cannot be updated!" >&2
        sleep 5s
    fi

    if grep -q 'systemd.unit=steamos-update-os.target' /proc/cmdline; then
        steamos-logger "Rebooting in 5 seconds...";
        sleep 5s
        reboot
    else
        echo "Reboot to run the new version of SteamOS." >&2
    fi
}

update_after_reboot() {
    touch /run/steamos/update-other
    echo "Reboot to start the update of SteamOS." >&2
}

if [[ $# -eq 0 ]]; then
    usage
    exit 1
fi

case "$1" in
    (now)
        shift
        update_now "$@"
        ;;
    (after-reboot)
        shift
        update_after_reboot
        ;;
    (-h|--help)
        usage
        exit 0
    (*)
        usage
        exit 1
        ;;
esac
