#!/bin/bash

echo2() { echo "$@" >&2 ; }
DIE()   { echo2 "Error: $1"  ; exit 1 ; }
WARN()  { echo2 "Warning: $1" ; }
Pushd() { pushd "$@" >/dev/null || DIE "'pushd $*' failed." ; }
Popd()  { popd  "$@" >/dev/null || DIE "'popd $*' failed." ; }

Main() {
    echo2 "Creating a 'release assets build environment' for the repo in the current (git) folder."
    test -d .git || DIE "this folder ($PWD) does not have a .git subfolder." 

    local gitdir="$PWD"
    local builddirbase="$gitdir/../_BUILD_/$(basename "$gitdir")"
    local builddir
    
    local confurls="https://github.com/endeavouros-team/PKGBUILDS/raw/master/eos-pkgbuild-setup"   # configs are here
    local conf

    local reponame=$(grep "url =" .git/config | awk '{print $NF}')
    reponame="${reponame##*/}"  # remove head
    reponame="${reponame%.*}"   # remove tail

    local tags="$(hub release)"
    local tag
    local suffix
    local dirscreated=()
    local sigfile sigend=sig

    for tag in $tags ; do
        #if [ "$reponame|$tag" = "mirrors|mirror2" ] ; then
        #    continue         # create only one build env for mirror1 and mirror2 (assets are the same)
        #fi
        suffix="$reponame.$tag"
        builddir="$builddirbase.$tag"             # uses local dirname, may not be reponame...
        conf="${confurls}/assets.conf.$suffix"

        mkdir -p "$builddir"
        
        Pushd "$builddir"

        wget -q --timeout=10 "$conf" || {
            Popd
            WARN "file '$conf' not found."
            rmdir "$builddir"
            continue
        }
        wget -q --timeout=10 "$conf".$sigend || {
            Popd
            WARN "file '$conf.$sigend' not found."
            rmdir "$builddir"
            continue
        }
        sigfile="$(basename "$conf.$sigend")"
        test -r "$sigfile" && {
            gpg --verify "$sigfile" || DIE "$sigfile: signature check failed!"
            rm -f "$sigfile"
            mv "assets.conf.$suffix" "assets.conf"
        }
        Popd

        dirscreated+=("$builddir")
    done

    echo2 "The following build folders were created:"
    for builddir in "${dirscreated[@]}" ; do
        echo2 "    $builddir"
    done
    echo2 "Assets can be built in them with these commands:"
    echo2 "    cd <build-folder>"
    echo2 "    assets.make"
}

Main "$@"
