#! /bin/bash
#########################################################################
#									#
#	oscbuilder is automatically generated,				#
#		please do not modify!					#
#									#
#########################################################################

#########################################################################
#									#
# Author: Copyright (C) 2022-2024  Mark Grant				#
#									#
# Released under the GPLv3 only.					#
# SPDX-License-Identifier: GPL-3.0-only					#
#									#
# Purpose:								#
# A helper script to perform an osc build.				#
#									#
# Syntax:	See usage().						#
#									#
# Exit codes used:-							#
# Bash standard Exit Codes:	0 - success				#
#				1 - general failure			#
# User-defined exit code range is 64 - 113				#
#	C/C++ Semi-standard exit codes from sysexits.h range is 64 - 78	#
#		EX_USAGE	64	command line usage error	#
#		EX_DATAERR	65	data format error		#
#		EX_NOINPUT	66	cannot open input		#
#		EX_NOUSER	67	addressee unknown		#
#		EX_NOHOST	68	host name unknown		#
#		EX_UNAVAILABLE	69	service unavailable		#
#		EX_SOFTWARE	70	internal software error		#
#		EX_OSERR	71	system error (e.g., can't fork)	#
#		EX_OSFILE	72	critical OS file missing	#
#		EX_CANTCREAT	73	can't create (user) output file	#
#		EX_IOERR	74	input/output error		#
#		EX_TEMPFAIL	75	temp failure; user is invited	#
#					to retry			#
#		EX_PROTOCOL	76	remote error in protocol	#
#		EX_NOPERM	77	permission denied		#
#		EX_CONFIG	78	configuration error		#
#	User-defined (here) exit codes range 79 - 113:			#
#		None							#
#									#
# Further Info:								#
#									#
#########################################################################


set -eo pipefail


##################
# Init variables #
##################
readonly version=1.1.1				# Script version
readonly packageversion=1.2.1		# Package version

arch="x86_64"					# Default architecture
base_output_dir=""
cla=()
readonly conffile=/etc/obs-utils-mge.conf
repo=""


#############
# Functions #
#############

# -h --help output.
# No parameters
# No return value
usage()
{
cat << EOF
Usage is:-
$(basename "$0") [-a] [-r] [-- PASS_THRU_OPTIONS ...]
$(basename "$0") {-h|-V}
Usage is:-
$(basename "$0") [OPTIONS] [-- PASS_THRU_OPTIONS ...]
	-a or --arch 'arch-name' Target architecture
	-h or --help Display this help information
	-r or --repo 'Repository'
	-V or --version Print script version information
	-- then params to pass directly to osc build

Example
	$(basename "$0") -r Fedora_35 -a x86_64 -- --no-verify
EOF
}

# Standard function to emit messages depending on various parameters.
# Parameters -	$1 What:-	The message to emit.
#		$2 Where:-	stdout == 0
#				stderr == 1
# No return value.
output()
{
	if (( !$2 )); then
		printf "%s\n" "$1"
	else
		printf "%s\n" "$1" 1>&2
	fi
}

# Standard function to tidy up and return exit code.
# Parameters - 	$1 is the exit code.
# No return value.
script_exit()
{
	exit "$1"
}

# Standard function to test command error and exit if non-zero.
# Parameters - 	$1 is the exit code, (normally $? from the preceeding command).
# No return value.
std_cmd_err_handler()
{
	if (( $1 )); then
		script_exit "$1"
	fi
}

# Standard trap exit function.
# No parameters.
# No return value.
# shellcheck disable=SC2317  # Do not warn about unreachable commands in trap
# functions, they are legitimate.
trap_exit()
{
	local -i exit_code=$?
	local msg

	msg="Script terminating with exit code $exit_code due to trap received."
	output "$msg" 1
	script_exit" $exit_code"
}

# Setup trap
trap trap_exit SIGHUP SIGINT SIGQUIT SIGTERM


# Process config file.
# No parameters.
# No return value.
proc_config_file()
{
	local old_IFS
	local read_base_output_dir

	if [[ ! -f $conffile ]]; then
		output "Config file $conffile does not exist." 1
		script_exit 77
	fi
	if [[ ! -r $conffile ]]; then
		output "Incorrect permissions for config file $conffile." 1
		script_exit 77
	fi

	old_IFS=$IFS
	IFS="="
	exec 3<$conffile
	while read -u3 -ra input; do
		# Discard comment lines.
		[[ "${input[0]}" =~ ^[[:blank:]]*# ]] && continue
		case ${input[0]} in
		base_output_dir)
			read_base_output_dir=${input[1]}
			;;
		esac
	done
	exec 3<&-
	IFS=$old_IFS

	if [[ "${read_base_output_dir:0:1}" == "~" ]]; then
		base_output_dir="${HOME}${read_base_output_dir:1}"
	else
		base_output_dir="${read_base_output_dir}"
	fi

	if [[ ! -d $base_output_dir ]]; then
		output "Config file output dir not a directory." 1
		script_exit 77
	fi
	if [[ ! -r $base_output_dir ]]; then
		output "Incorrect permissions for base output directory." 1
		script_exit 77
	fi
}

# Process command line arguments with GNU getopt.
# Parameters -	$1 is the command line.
# No return value.
proc_CL()
{
	local GETOPTTEMP
	local msg
	local tmp

	tmp="getopt -o a:hr:V --long arch:,help,repo:,version"
	GETOPTTEMP=$($tmp -n "$0" -- "$@")
	std_cmd_err_handler $?

	eval set -- "$GETOPTTEMP"
	std_cmd_err_handler $?

	while true; do
		case "$1" in
		-a|----arch)
			arch=$2
			shift 2
			;;
		-h|--help)
			usage
			shift
			script_exit 0
			;;
		-r|--repo)
			repo=$2
			shift 2
			;;
		-V|--version)
			printf "%s Script version %s\n" "$0" $version
			printf "%s Package version %s\n" "$0" $packageversion
			shift
			script_exit 0
			;;
		--)	shift
			break
			;;
		*)	output "Internal error." 1
			script_exit 64
			;;
		esac
	done

	# Preserve remaining arguments. All remaining arguments are passed
	# straight to the osc build command line, (to support things like
	# --no-verify... etc).
	if (( $# )); then
		cla=( "$@" )
	fi
}

# If no repo set on CL, default to current distribution.
set_dist_default()
{
	local id
	local os_release_file
	local version_id

	if [[ $repo = "" ]]; then
		os_release_file="/etc/os-release"
		if [ ! -e "$os_release_file" ]; then
			os_release_file="/usr/lib/os-release"
		fi
		id=$(sed -n '/^ID=/s/^.*=//p' $os_release_file \
			| sed -e 's/"//g')
		version_id=$(sed -n '/^VERSION_ID=/s/^.*=//p' $os_release_file \
			| sed -e 's/"//g')
		if [[ $id == "debian" ]]; then
			repo="Debian_$version_id"
		elif [[ $id == "fedora" ]]; then
			repo="Fedora_$version_id"
		elif [[ $id == "opensuse-leap" ]]; then
			repo="$version_id"
		elif [[ $id == "raspbian" ]]; then
			repo="Raspbian_$version_id"
		fi
	fi
}


########
# Main #
########

proc_config_file

proc_CL "$@"

set_dist_default

osc build -k "$base_output_dir/$repo/$arch/built-pkgs" \
	-p "$base_output_dir/$repo/$arch/tmp-pkg-cache" \
	"$repo" "$arch" "${cla[@]}"

# And exit.
script_exit 0

