#!/usr/bin/env bash
# Copyright (c) 2024 Celestino Amoroso (celestino.amoroso@gmail.com).
# All rights reserved.

RESOURCE_FILE=".build.rc"
BUILD_REGISTER=".build_register"
PASSWORD=
GITEA_USER="camoroso"
GITEA_PASSWORD_FILE="${HOME}/.gitea_password"
GITEA_OWNER="go-pkg"
GITEA_HOST="https://git.portale-stac.it"
GITEA_BASE_PATH="api/packages"
GITEA_PKG_TYPE="generic"

function exitMsg() {
	echo >&2 "${1}"
	exit 1
}

function readBuildCount() {
	local reg ver count
	if [ -r "${BUILD_REGISTER}" ]; then
		reg=$(<"${BUILD_REGISTER}")
	else
		reg="${PROGRAM_VERSION} 0"
	fi
	read ver count <<<"${reg}"
	if [ "${ver}" != "${PROGRAM_VERSION}" ]; then
		count=0
	fi
	echo ${count}
}

if [ -r "${GITEA_PASSWORD_FILE}" ]; then
	if ! PASSWORD=$(<"${GITEA_PASSWORD_FILE}"); then
		exitMsg "Can're password file '${GITEA_PASSWORD_FILE}'"
	fi
else
	exitMsg "Password file '${GITEA_PASSWORD_FILE}' not found"
fi
if [ -z "${PASSWORD}" ]; then
	exitMsg "Empty password. Please, check file '${GITEA_PASSWORD_FILE}'"
fi

if ! ./build.bash; then
	exitMsg "Build program failed"
fi

if ! source "${RESOURCE_FILE}"; then
	exitMsg "Loading resource file failed"
fi

if ! exeList=$(echo 2>/dev/null ${PROGRAM_NAME}_v${PROGRAM_VERSION}_*); then
	exitMsg "No executable found"
fi

buildCount=$(readBuildCount)
fileCount=0
for exe in ${exeList}; do
	if [ "${exe/tar.gz/}" != "${exe}" ]; then
		continue
	fi
	((fileCount++))
	dir="${exe}_${buildCount}"
	dist="${dir}.tar.gz"
	rm -f "${dist}"
	printf "%2d: %-30s  -->  %s\n" "${fileCount}" "${exe}" "${dist}"
	mkdir "${dir}"
	cp "${exe}" "${dir}/${PROGRAM_NAME}"
	tar czf "${dist}" "${dir}"
	rm -fR "${dir}"

	url="${GITEA_HOST}/${GITEA_BASE_PATH}/${GITEA_OWNER}/${GITEA_PKG_TYPE}/${PROGRAM_NAME}/${PROGRAM_VERSION}/${dist}"
#	echo "${url}"
	curl --user "${USER}:${PASSWORD}" --upload-file "${dist}" "${url}"

	rm -f "${dist}"
done

