#!/bin/bash

# The Steam client is known to call this script with the following parameter combinations:
# steamos-update --supports-duplicate-detection     -- should do nothing
# steamos-update --enable-duplicate-detection check -- should check for update
# steamos-update check                              -- should check for update
# steamos-update --enable-duplicate-detection       -- should perform an update
# steamos-update                                    -- should perform an update


while [[ $# -gt 0 ]]; do
  case $1 in
    check)
      CHECK=1
      shift
      ;;
    --supports-duplicate-detection)
      EXIT=1
      shift
      ;;
    *)
      shift
      ;;
  esac
done


if command -v ublue-update > /dev/null; then
  if [ -n "${CHECK}" ]; then
    if [ -f '/tmp/upgrade-installed' ]; then
      exit 7 # Upgrade already installed
    else
      # Perform connectivity check
      wget -q --spider https://github.com
      if [ $? -eq 0 ]; then
        # Check system state
        ublue-update --check --updatecheck
        if [ $? -eq 0 ]; then
          exit 0 # Upgrade available
        else
          exit 7 # Checks failed
        fi
      else
        exit 7 # Connectivity check failed
      fi
    fi
  elif [ -n "${EXIT}" ]; then
    exit 0
  else
    # Fake upgrade progress bar
    fake_progress() {
      local value=0
      while [ ! -f '/tmp/upgrade-check' ]; do
        sleep 10
        if [ ${value} -lt '100' ]; then
          echo ${value}'%'
          value=$(( value + 1 ))
        fi
      done
      echo 100%
    }
    upgrade() {
      # Pull exit code from ublue-update
      systemctl start ublue-update-force > /dev/null 2>&1
      echo $? > /tmp/upgrade-check
    }
    upgrade | fake_progress
    # Check if upgrade failed
    UPGRADE_CHECK=/tmp/upgrade-check
    rm /tmp/upgrade-check
    if [ ${UPGRADE_CHECK} -eq 0 ]; then
      touch /tmp/upgrade-installed
    else
      exit 0 # Upgrade failed
    fi
  fi
else
  exit 7 # ublue-update not installed
fi
