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


RESOURCE_FILE=".build.rc"
BUILD_REGISTER=".build_register"

PROGRAM_NAME=""
PROGRAM_VERSION=""

function usage() {
	prog=$(basename "${0}")
	msgln "USAGE:"
	#msgln "      ${prog} <program-name> <program-version> <os>/<platform>..."
	msgln "      ${prog} <os>/<platform>..."
	msgln "      ${prog} --local         Build the local exec"
	msgln "      ${prog} --init          Create the resource file in the current directory"
	msgln
	if [ -r "${RESOURCE_FILE}" ]; then
		msgln "Resource file '${RESOURCE_FILE}' content:"
		cat >&2 ${RESOURCE_FILE}
	else
		msgln "Resource file '${RESOURCE_FILE}' not found"
	fi
}

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

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

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

# CMDLINE: help
if [ "${1}" == "help,," ] || [ "${1,,}" == "--help" ] || [ "${1,,}" == "-h" ]; then
	usage
	exit
fi

# CMDLINE: init
if [ "${1,,}" == "--init" ]; then
	cat >"${RESOURCE_FILE}" <<eot
# Builder resource file
# Created on $(date)

# Program name
PROGRAM_NAME="name"

# Program version
PROGRAM_VERSION="version"

# Preset platform
platform=("linux/amd64" "darwin/arm64")

#--- end of file ---

eot
	msgln "Resource file '${RESOURCE_FILE}' create. Edit it to set valid values."
	#${EDITOR-vi} "${RESOURCE_FILE}"
	exit
fi

if [ -r "${RESOURCE_FILE}" ]; then
	if ! source "${RESOURCE_FILE}"; then
		exitMsg "Can't load build resource file '${RESOURCE_FILE}'"
	fi
fi

if [ -z "${PROGRAM_NAME}" ]; then
	exitUsage "Missing program name"
fi

if [ -z "${PROGRAM_VERSION}" ]; then
	exitUsage "Missing program version"
fi


function getBuildCount() {
	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
	count=$((count+1))
	echo >"${BUILD_REGISTER}" "${PROGRAM_VERSION} ${count}"
	echo ${count}
}

function build() {
	local target=${1} ext cmd
	IFS=/ read os cpu <<<"${p}"
	#msgln "OS=${os}; CPU=${cpu}"
	ext=""
	if [ "${os}" == 'windows' ]; then
		ext=".exe"
	fi
	cmd="GOOS='${os}' GOARCH='${cpu}' go build -o '${PROGRAM_NAME}_v${PROGRAM_VERSION}_${os}_${cpu}${ext}'"
	eval "${cmd}"
}

function buildLocal() {
	local ext cmd
	ext=""
	if [[ "${OSTYPE}" =~ win.* ]]; then
		ext=".exe"
	fi
	cmd="go build -o '${PROGRAM_NAME}${ext}'"
	eval "${cmd}"
}

function gitTag() {
	local gopath gopkg mod
	local tag

	if ! tag=$(git tag -l --sort=-version:refname "v[0-9]*.[0-9]*.[0-9]*"|head -1) || [ -z "${tag}" ]; then
		gopath=$(go env GOPATH)
		gopkg="${gopath}/pkg/mod/git.portale-stac.it/go-pkg"
		if cd "${gopkg}" 2>/dev/null; then
			mod=$(ls -1v |grep expr@|tail -1)
			tag=${mod##*@}
			cd - >/dev/null
		fi
	fi
	echo ${tag}
}

function gitTagDate() {
	local tag_name=${1}
	local tag_date

	if ! tag_date=$(git show --no-patch --format=%ci "${tag_name}") || [ -z "${tag_date}" ]; then
		tag_date="n/a"
	fi
	echo ${tag_date}
}

function createVersionSource() {
	local tag tag_date
	tag=$(gitTag)
	if [ -z "${tag}" ]; then
		tag="n/a"
	else
		tag_date=$(gitTagDate "${tag}")
	fi

	cat >version.go <<eot
// Copyright (c) 2024-$(date +%Y) Celestino Amoroso (celestino.amoroso@gmail.com).
// All rights reserved.

// version.go
package main

const (
	PROGNAME     = "${PROGRAM_NAME}"
	VERSION      = "v${PROGRAM_VERSION}(build $(getBuildCount)),$(date +"%Y/%m/%d") (celestino.amoroso@portale-stac.it)"
	EXPR_VERSION = "${tag}"
	EXPR_DATE    = "${tag_date}"
)
eot
}

## -- TEST -- ##

# echo "Tag: $(gitTag)"
# echo "Tag Date: $(gitTagDate $(gitTag))"
# exit 0

## -- MAIN -- ##
createVersionSource

if [ "${1}" == "--local" ]; then
	buildLocal
	exit
fi

if [ ${#} -gt 0 ]; then
	for p; do
		build "${p}"
	done
else
	for p in ${platform[@]}; do
		build "${p}"
	done
fi

