#!/bin/sh
# File: make-issue.sh
# Location: /mnt/public/work/git.devuan.org
# Author: bgstack15
# Startdate: 2024-07-02-3 10:26
# Title: Begin Build of Package in Devuan CI
# Purpose: make a oneliner to submit a build task for a project I maintain in Devuan
# History:
# Usage:
#    ./make-issue.sh lightdm
# Reference:
#    https://docs.gitea.com/api/1.20/#tag/organization/operation/orgGetLabel
#    https://demo.gitea.com/api/swagger#/issue/issueCreateIssue
#    https://docs.gitea.com/developers/api-usage
# Improve:
# Dependencies:
#    devuan-req: curl, jq

TOKEN="$( cat /mnt/public/packages/git.devuan.org-token )"
SUITE="${SUITE:-unstable}"
GITEAURL="${GITEAURL:-https://git.devuan.org}"
REPO="${REPO:-${1}}"

main() {
   # input: SUITE, TOKEN, REPO
   # Purpose: print the build job url, e.g, https://jenkins.devuan.dev/job/devuan-package-builder/2015
   # get label id of suite we want to use.
   test -z "${REPO}" && { echo "Fatal! Must set REPO. Aborted." ; return 1 ; }
   response="$( curl --silent "${GITEAURL%%/}/api/v1/orgs/devuan/labels" )"
   label_id="$( echo "${response}" | jq ".[] | select(.name == \"${SUITE}\").id" )"
   response="$( curl --silent "${GITEAURL%%/}/api/v1/repos/devuan/${REPO}/issues" -X POST -H "Accept: application/json" -H "Authorization: token ${TOKEN}" -H "Content-Type: application/json" --data-raw \
      "{\"description\":\"\",\"labels\":[${label_id}],\"title\":\"build\",\"assignees\":[\"releasebot\"]}"
   )"
   issue="$( echo "${response}" | jq '.number' )"
   sleep 8 # to give releasebot time to add its comment
   response="$( curl --silent "${GITEAURL%%/}/api/v1/repos/devuan/${REPO}/issues/${issue}/comments" -X GET -H "Accept: application/json" -H "Authorization: token ${TOKEN}" )"
   buildjob="$( echo "${response}" | jq --raw-output '.[] | select(.user.login = "ReleaseBot") | select(.body | startswith("Triggered")).body' | sed -r -e 's/^.*(https?)/\1/;' )"
   echo "${buildjob}"
}

# check if dot-sourced:
# Ref: https://stackoverflow.com/questions/2683279/how-to-detect-if-a-script-is-being-sourced/28776166#28776166
sourced=0
if [ -n "$ZSH_VERSION" ]; then 
  case $ZSH_EVAL_CONTEXT in *:file) sourced=1;; esac
elif [ -n "$KSH_VERSION" ]; then
  [ "$(cd -- "$(dirname -- "$0")" && pwd -P)/$(basename -- "$0")" != "$(cd -- "$(dirname -- "${.sh.file}")" && pwd -P)/$(basename -- "${.sh.file}")" ] && sourced=1
elif [ -n "$BASH_VERSION" ]; then
  (return 0 2>/dev/null) && sourced=1 
else # All other shells: examine $0 for known shell binary filenames.
     # Detects `sh` and `dash`; add additional shell filenames as needed.
  case ${0##*/} in sh|-sh|dash|-dash) sourced=1;; esac
fi

# if not dot-sourced:
if test $sourced -eq 0 ;
then
   test -z "${REPO}" && { echo "Fatal! Must set REPO. Aborted." ; exit 1 ; }
   main
fi
