#!/bih/sh

#
# Qt4 distribution RPM archive creator.
#
# NOTE: This script requires the basic set of unix tools such as cp, mkdir,
# pwd, readlink, find etc.
#

#
# Defaults
#

qt_spec=qt.spec

#
# Functions
#

die() { echo "ERROR: $@"; cd "$start_dir"; exit 1; }

run()
{
    echo "$@"
    "$@" || die \
"Last command failed (exit status $?)."
}

cmd_all()
{
    local src_base="$1"

    [ -d "$src_base" ] || die "'$src_base' is not a directory."

    run $env_cmd rpmbuild \
        -D "QT_SOURCE_TREE $src_base" \
        -ba $qt_spec
}

cmd_build()
{
    local src_base="$1"

    [ -d "$src_base" ] || die "'$src_base' is not a directory."

    run $env_cmd rpmbuild \
        -D "QT_SOURCE_TREE $src_base" -D "skip_prep_export 1" \
        -bc $qt_spec
}

cmd_rpm()
{
    local inst_base="$1"

    [ -d "$inst_base" ] || die "'$inst_base' is not a directory."

    run $env_cmd rpmbuild \
        -D "QT_BUILD_TREE $inst_base" \
        --short-circuit -bi $qt_spec
}

#
# Main
#

script_path=$(readlink -e $0)
script_dir=${script_path%/*}
script_name=$(basename $0)

start_dir=$(pwd)

[ -f "$start_dir/env.sh" ] && . "$start_dir/env.sh"

env_cmd=
[ -f "$start_dir/env.cmd" ] && env_cmd="cmd /c env.cmd"

# Parse arguments

cmd_help()
{
    echo \
"
Usage:
  $script_name all <srcdir>     Do everything (RPM, SRPM, ZIP)
  $script_name build <srcdir>   Build product (shadow build)
  $script_name rpm [<instdir>]  Build RPMs only

Options:
  <srcdir>      Qt SVN source tree location
  <instdir>     Qt installation tree location
                (default: $HOME/rpmbuild/BUILDROOT/qt-X.Y.Z)
"
}

case "$1" in
    all|build)
        if [ -n "$2" ]; then
            cmd_$1 $(echo "$2" | tr '\\' '/')
        else
            cmd_help
        fi;;
    rpm)
        if [ -n "$2" ]; then
            cmd_rpm $(echo "$2" | tr '\\' '/')
        else
            cmd_rpm
        fi;;
    -h|-?|--help|*) cmd_help;;
esac

# end of story

exit 0
