#!/usr/bin/bash
#
# Build packages in approved queues.
#

scriptdir=$( dirname $(readlink -fn $0))
source $scriptdir/lpf-defs.bash


function get_approving_user()
# get_approving_user <pkg>: return user who approved package, or 'unknown'.
{
    local approve_file=$( get_approve_file $1 )
    ls -l $approve_file 2>/dev/null | awk '{print $3}' ||  echo 'unknown'
}


function done_msg()
# done_msg <pkg> <state>: Print "Build completed" (OK or fail) with or
# without GUI.
{
    local pkg=$1 state=$2
    if [ "$state" == 'install-wait' ]; then
        if [[ -n "$DISPLAY" && -z "$LPF_UPDATE" ]]; then
            zenity --info --title "Build completed OK"
        else
            echo "$pkg: build completed, no errors"
        fi
    else
        if [ -n "$DISPLAY" ]; then
            reply=$( $scriptdir/build_error )
            if [ "$reply" = "view_buildlog" ]; then
                zenity --text-info --filename $(get_logfile $1)  \
                    --width 600 --height 500
            fi
        else
            echo "$pkg: build failed (use lpf log to view log)" >&2
        fi
    fi
}

trap "do_trap 82" SIGINT ERR
export NO_AT_BRIDGE=0

readonly pkgdirs=( $(get_arg_pkgdirs $@) )


for pkgdir in ${pkgdirs[@]}; do
    exec 5<&1 6<&2  # Preserve  original stdout/stderr.
    source $scriptdir/../CONFIG
    [ -f $pkgdir/CONFIG ] && source $pkgdir/CONFIG
    pkg=${pkgdir##*/}
    buildlog=$( get_logfile $pkg )
    user=$( get_approving_user $pkg )
    spec=$pkgdir/$pkg.spec
    state=$( get_state $pkg )
    if [[ $state == build-wait && "$user" != unknown ]]; then
        exec &> $buildlog
        echo "$pkg: installing build dependencies" >&5 &&
            $SUDO $scriptdir/lpf-sudo-builddep $spec &&
            exec 1<&5 2<&6 &&
            $scriptdir/lpf-pkgbuild 'build' $pkg
        exec 1<&5 2<&6
        state=$( get_state  $pkg )
        done_msg $pkg $state
        [ "$state" != 'install-wait' ] && exit 1
    fi
done
exit 0


# vim: set expandtab ts=4 sw=4:
