#!/bin/bash

# List of architectures and commands to build.
# Interpreted as a list of steps to execute. Each instruction is separated by a comma.
# Elements containing a colon: <target>:<args> - build <target> using <args> to Mymake.
# Elements containing an at sign: treated as a hostname, SSH there and continue build.

# Convenience for specifying build configuration. Commas will be inserted between each line.
ARCHLIST=(
    "mps_win32:mps"
    "smm_win32:smm"
    "mps_win64:mps 64"
    "build@rpi"
    "mps_arm64:mps"
    "build@nas"
    "mps_amd64:mps"
    "smm_amd64:smm"
    "filip-www@fprg.se"
    "done"
)
function join_array { local IFS=","; echo "$*"; }
ARCHLIST=$(join_array "${ARCHLIST[@]}")

completed=false

function remove_tag {
    if [[ $completed == false ]]
    then
	echo "Build failure. Removing the created tag..."
	echo "$version" > release_message.txt
	echo "" >> release_message.txt
	git cat-file -p release/$version | tail -n +6 >> release_message.txt
	git tag --delete release/$version
	echo "Release message in file release_message.txt"
    fi
}


branch=$(git rev-parse --abbrev-ref HEAD)
if [[ $branch != "master" ]]
then
    echo "Error: You need to checkout the branch 'master' to perform a release."
    exit 1
fi

version=$(find_version)
read -p "Current version is $version. Change it? [Y/n] " -n 1 -r
echo
if [[ $REPLY =~ ^[Yy]$ ]] || [[ -z $REPLY ]]
then
    create_version
    version=$(find_version)
    trap remove_tag EXIT
fi


hash=$(git rev-parse HEAD)

date=$(git for-each-ref "refs/tags/release/${version}" --format="%(taggerdate:iso)" | cut -d" " -f 1)


release-build-doc "$version" "$date" || exit 1

release-step "$ARCHLIST" "$version" "$date" "$hash" || { echo "Build failed. Try again!"; exit 1; }

completed=true
echo "Finished! Remember to push tags!"
