#!/bin/sh
#
# init_rpm_build
#

VERSION="1.3"

show_help()
{
    cat <<EOF

Prepare to build RPMs from the Husky sources.

Usage:.
    init_rpm_build [-d|--dir TOP_DIRECTORY] [-v|--version] [-h|-\?|--help]
Options:
    -d TOP_DIRECTORY
    --dir TOP_DIRECTORY
        Put all Husky sources in TOP_DIRECTORY. It should be an absolute path.

    -v
    --version
        Print the script version and exit.

    -h
    -?
    --help
        Print this help and exit.
EOF
}

die()
{
    printf '%s\n' "$1" >&2
    exit 1
}

top_directory=~/husky_build
help=0

case $1 in
    -h|-\?|--help)
        help=1
        ;;
    -v|--version)
        echo "version = $VERSION"
        exit
        ;;
    -d|--dir)
        if [ "$2" ]
        then
            top_directory="$2"
            [ "${top_directory%"${top_directory#?}"}" != '/' ] && \
                [ "${top_directory%"${top_directory#??}"}" != '~/' ] && \
                die 'ERROR: the directory must start with "/" or "~/"'
            shift
        else
            die 'ERROR: "-d" or "--dir" requires a non-empty option argument'
        fi
        ;;
    -*)
        printf 'WARN: Unknown option (ignored): %s\n' "$1" >&2
        ;;
    *)
        ;;
esac

n=0
if [ -z "$(whereis -b git | cut -d: -f2)" ]
then
    echo Please install git
    n=1
fi
if [ -z "$(whereis -b mock | cut -d: -f2)" ]
then
    if [ -z "$(whereis -b rpmbuild | cut -d: -f2)" ]
    then
        echo "If you can install mock, please install it."
        echo "Otherwise, if you cannot install mock, please install rpmbuild."
        n=1
    else
        echo "Since mock is not installed, rpmbuild will be used."
    fi
fi
[ "$n" -eq 1 ] && exit 1

# Check that the script is not run by root
[ "$(id -u)" -eq 0 ] && die "DO NOT run this as root"

[ "${top_directory%?}/" = "${top_directory}" ] && top_directory="${top_directory%?}"
mkdir -p $top_directory
cd $top_directory
mkdir husky
cd husky
git clone https://github.com/huskyproject/huskybse.git

cp -a huskybse/Makefile Makefile
cp -a huskybse/husky.spec.in husky.spec.in
cp -a huskybse/huskymak.rpm.cfg huskymak.cfg
cp -a huskybse/huskymak.rpm.cfg ../huskymak.rpm.cfg.new
cp -a huskybse/script/spec_configure ../spec_configure
cp -a huskybse/script/build_rpm ../build_rpm
echo
echo "########################################################################"
echo "Now you need to make changes to \"$top_directory/husky/huskymak.cfg\""
echo "per your requirements and then run \"$top_directory/build_rpm\"."
echo "########################################################################"
echo
