#!/bin/bash4 -efuC
set -o pipefail

MY="$(realpath "$0")"
MY="${MY%/*}"
readonly MY

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

    local num=
    case "${1-}" in
		# The pattern is not precise (wanted: all digits)
		-[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

    mkdir -p error success

	local f exactP
	# altlinux-repolist-src-names-to-src-files expects that:
	# 1. there is a .../files/list/src.list;
	# 2. the files are in .../files/SRPMS/
	# The shown path components are obligatory.
	# Therefore, not any dir with srpms can be given as SRPMDIR. (FIXME!)
    f="$(altlinux-repolist-src-names-to-src-files ${SRPMDIR:+--repo "${SRPMDIR%/files/SRPMS}"/files/list} "$p")"
	local -r f
    exactP="$(basename "${f%%.src.rpm}")"
	local -r exactP

    #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 "$@"
