#!/bin/bash4 -e

MY="$(dirname "$(realpath "$0")")"
readonly MY

. "$MY"/rebuild-functions.sh

rebuild1() {
    if [[ -x ./hsh ]]; then
	local -r HSH=./hsh
    else
	local -r HSH=hsh
    fi

    local num=
    case "$1" in
	-*([0-9])) num="${1#-}"; shift;;
    esac

    local -r p="$1"
    shift

    # Shorter message (without exactP) is more human-readable
    # (and can be printed earlier):
    echo ${num:+"[$num]"} "$p" rebuild start

    # If there has been a SUCCESSful build already,
    # we want to SKIP based on $p (without ver-rel).
    if [[ -r srpms-to-skip ]] &&
	fgrep -q --line-regexp "$p" <srpms-to-skip
    then
	echo ${num:+"[$num]"} "$p" rebuild SKIP
	exit 0
    fi


    if [[ -z "$SRPMDIR" ]]; then
	SRPMDIR=/ALT/Sisyphus/files/SRPMS
    fi

    mkdir -p error success

    local -r f="$(getFileForPkgname "$SRPMDIR"/ "$p" .src.rpm)"
    local -r exactP="$(basename "${f%%.src.rpm}")"

    #echo "$exactP start"

    # If it is known that the package FAILED TO BUILD in Sisyphus,
    # we want to SKIP based on $exactP: perhaps,
    # it has been fixed already in a new release.
    if [[ -r srpms-to-skip ]] &&
	fgrep -q --line-regexp "$exactP" <srpms-to-skip
    then
	echo ${num:+"[$num]"} "$exactP" rebuild SKIP
	exit 0
    fi

    local -r out=building$num-"$exactP".log
    if "$HSH" ${num:+--number=$num} ~/hasher$num "$f" &>"$out"; then
	echo ${num:+"[$num]"} "$exactP" rebuild SUCCESS
	mv "$out" success/"$exactP"
    else
	echo ${num:+"[$num]"} "$exactP" rebuild ERROR
	mv "$out" error/"$exactP"
    fi

    echo "$exactP" >>srpms-build-attempted
}

rebuild1 "$@"
