#!/bin/bash

set -eu

##
## This script must match the API the temporary Steam UI updater wants of us, including this file
##

unset tmpdir
cleanup() { rm -rf /tmp/steamos-update.pid; [[ -z ${tmpdir-} ]] || rm -rf --one-file-system -- "$tmpdir"; }
trap cleanup EXIT
touch /tmp/steamos-update.pid
info() { echo >&2 "$*"; }
die() { info "!! $*"; exit 1; }


checkmode=""
error=""
beta=""

while [[ $# -ge 1 ]]; do
  case "$1" in
    "check") checkmode=1 ;;
    "--beta") beta=1 ;;
    *)
      error=1
      info "Unknown option \"$1\""
    ;;
  esac
  shift
done

if [[ -n $error ]]; then
  echo >&2 "!! Usage: $0 [--beta] [check]"
  exit 1
fi

atomupd_args=(-d)

if [[ -n $beta ]]; then
  # Make beta version of our manifest and use it

  # $tmpdir is cleaned up by the exit hook above if we use it
  tmpdir="$(mktemp -d --tmpdir steamos-update.XXXX)"
  [[ -n $tmpdir && -d $tmpdir ]] || die "Could not create a temporary directory"

  manifest="$tmpdir"/manifest.json
  sed -r s/steamdeck/steamdeck-beta/ /etc/steamos-atomupd/manifest.json > "$manifest"
  atomupd_args+=(--manifest "$manifest")
fi

do_atomupd() { sudo steamos-atomupd-client "${atomupd_args[@]}" "$@"; }

query="$(do_atomupd --query-only)"
if [[ -z $query ]]; then
  info "Failed to check for updates"
  exit 1 # Unknown failure
fi

if [[ $query = "{}" ]]; then
  info "No update available"
  exit 7
fi

# Update is available
info "Update available"

# Check mode, return success for update available
if [[ -n ${checkmode-} ]]; then
  jq -r '.minor.candidates[0].image.buildid | select(type == "string")' <<< "$query"
  exit 0
fi

if do_atomupd; then
  info "Applied an update"
  exit 0
else
  info "Update failed"
  exit 1
fi
