#!/usr/bin/env bash

# set -x

[[ "$0" == /* ]] && typeset -r PRG=$0 || typeset -r PRG=$PWD/$0

BINDIR=$(dirname "$PRG")
typeset -r BINDIR

W3M=/opt/homebrew/bin/w3m
AWK=/usr/bin/awk
CURL=/usr/bin/curl

source "${BINDIR}/lib/logging.sh"

TARGET="${1-11.4.88.0.1.207.1}"

log::info "TARGET:${TARGET}"

URL="http://grt.us.oracle.com/grt/webservice/grtList/?gate=240&show=All&gateName=S11.4-SRU&status=1&target=${TARGET}"

log::debug $URL

output=$(/opt/homebrew/bin/w3m "$URL" -M -cols 400 -graph -dump 2>&1)

out=$(echo "$output" | awk '/^Details.*Consolidation/ {found=1; next} found')

if [[ -z "$out" ]];
then
	# log::debug "output: ### $out ###"
	log::info "There are no queued RTIs for \"${TARGET}\". Nothing to do..."
	exit 0
fi


log::info "Opening the gate for ${TARGET}"

log::debug "Starting gate open for Ul11u4SRU"
log::debug "Target: \"${TARGET}\""

JENKINS_TOKEN='1154eb0158729a7d326c1db13e7dca0cea'
JENKINS_SERVER='http://mrshughes.us.oracle.com/jenkins/'

JOB_URL="${JENKINS_SERVER}/job/Solaris_11/job/11.4/job/userland-sru/job/userland-sru-gate-open-11.4/buildWithParameters"

log::info "Using '${JOB_URL}'"

$CURL -X POST "${JOB_URL}" \
	--user "pnyc:${JENKINS_TOKEN}" \
	--data-urlencode "Build_Label=${TARGET}" \
	--data-urlencode "hguser=petr.nyc@oracle.com" \
	--data-urlencode "dryrun=false" \
	--data-urlencode "verbose=true" \
	--data-urlencode "debug=true" \
	--data-urlencode "scriptdir=./solaris/userland/sru/" \
	--data-urlencode "do_gate_open=true"

log::info "The job will be started here:"
log::info "    ${JOB_URL%%buildWith*}"
