#!/usr/bin/bash
set -x
set -o pipefail

# Find the URL given by the user.
find_user_url() {
  local url=$1
  if [ -z "$1" ]; then
    url=$(grep '\(agama\|inst\).auto=' </run/agama/cmdline.d/agama.conf | awk -F ':?(inst|agama).auto=' '{sub(/ .*$/, "", $2); print $2}')
    echo $url
  else
    echo $1
  fi
}

# Try to import a profile from a list of URLs
import_profile() {
  local url=$1

  if [ -n "$url" ]; then
    echo "Using the profile located at $url"
    agama config generate "$url" | agama config load && return 0
  else
    urls=("label://OEMDRV/autoinst.jsonnet" "label://OEMDRV/autoinst.json" "label://OEMDRV/autoinst.xml" "file:///autoinst.jsonnet" "file:///autoinst.json" "file:///autoinst.xml")
    for url in "${urls[@]}"; do
      YAST_SKIP_PROFILE_FETCH_ERROR=1 agama config generate "$url" | agama config load && return 0
    done
  fi

  return 1
}

# Finish the process depending on the method selected by the user.
finish() {
  method=$(grep '\(agama\|inst\).finish=' </run/agama/cmdline.d/agama.conf | awk -F ':?(inst|agama).finish=' '{sub(/ .*$/, "", $2); print $2}')

  case "$method" in
  "stop" | "halt" | "poweroff")
    agama finish "$method"
    ;;
  *)
    agama finish
    ;;
  esac
}

# Temporarily skip the AutoYaST XML validation
export YAST_SKIP_XML_VALIDATION=1

url=$(find_user_url "$1")
import_profile $url

if [ 1 -eq $? ]; then
# Exit if a profile was not found.
  exit 0
fi

agama install
finish
