#!/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/v1/packages"
GITEA_PKG_TYPE="generic"


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

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 [ -r "${RESOURCE_FILE}" ]; then
	source "${RESOURCE_FILE}"
else
	exitMsg "resource file '${RESOURCE_FILE}' not found"
fi

if [ -r "${BUILD_REGISTER}" ]; then
	BUILD_TAG=$(<"${BUILD_REGISTER}")
else
	exitMsg "build register file '${BUILD_REGISTER}' not found"
fi
url="${GITEA_HOST}/${GITEA_BASE_PATH}/${GITEA_OWNER}/${GITEA_PKG_TYPE}/${PROGRAM_NAME}/${PROGRAM_VERSION}/files"
#echo "URL: ${url}"
#echo $(curl --user "${GITEA_USER}:${PASSWORD}" -X GET ${url}|jq '.[]."name"')

declare -a files=(
$(curl --no-progress-meter --user "${GITEA_USER}:${PASSWORD}" -X GET ${url}|jq '.[]."name"')
)

for name in ${files[@]}; do
	filename=${name:1:${#name}-2}
	name_terminal=${filename##*_}
	filever=${name_terminal%%.*}

	if [ "${BUILD_TAG}" != "${PROGRAM_VERSION} ${filever}" ]; then
		msgln "Deleting ${name}"
	curl --no-progress-meter --user "${GITEA_USER}:${PASSWORD}" -X DELETE ${GITEA_HOST}/api/packages/${GITEA_OWNER}/${GITEA_PKG_TYPE}/${PROGRAM_NAME}/${PROGRAM_VERSION}/${filename}
#	else
#		echo "most recent version"
	fi
done

#curl --user "${GITEA_USER}:${PASSWORD}" -X GET https://git.portale-stac.it/api/v1/packages/go-pkg/generic/ecli/1.7.0/files
