#! /bin/zsh -eu

# Bash can: setop pipefail

# see the previous tag for the Version.
# unless the debian/changelog contains the development
# version already.

#source @@SHAREDIR@@/functions
source /usr/share/build-system/functions.sh
eval $(possibly_trace)
check_getopt

export INSTALL_IMMEDIATELY=y
# during development it's better to install.
# --upgrade

FORCE=n

function usage(){
    setopt POSIX_ARGZERO
    cat >&2 <<EOF
usage: ${0##*/} [+-upbw] [--] ARGS...
    --mk-build-deps -m  install builddependencies (not checked??)
    --ignore -b  ... ignore branch
    --nosign -u  ... do not sign!
    --version -v  ... new version
    --source     ... create sourcd pkg as well (create the (ORIG) tarball)

    --install -i ... install immediately
           by default .... update only
    --noinstall

    --nocheck
    --keep -k       ... keep the build directory
    --work -w  ... use the work-directory of git.
EOF
    unsetopt POSIX_ARGZERO
}

# this exports to the `dput-install'! -- mmc: no!
DPUT_OPTIONS="-I"
USER_DISTRIBUTION=""
: ${DISTRIBUTION=UNRELEASED}
# export DISTRIBUTION

### Dput ... avoided
typeset -a GBP_OPTIONS
GBP_OPTIONS=()
typeset -a DCH_OPTIONS
DCH_OPTIONS=()

# default:
ignore_branch=y
do_sign=n
build_source=no
build_dependencies=no
typeset -a ARGS
ARGS=($@)

# A `leading' `:' in OPTSTRING causes getopts to store the letter of
# any invalid option in OPTARG, and to set NAME to `?' for an

# If a letter is `followed' by a `:', that option requires an argument.
# The options can be

cd $(git rev-parse --show-toplevel)
cmd_options=$(getopt --name $0 --shell bash \
    --longoptions help,ignore,sign,nosign,install,noinstall,pbuilder,version:,force,source,distro:,verbose,work,nocheck,keep,mk-build-deps \
    --options bd:fhikmnpstuVv:w \
    -- "$@" ) || { usage && exit 1 }
eval set -- "$cmd_options"

while (( $# > 0 )) do
    case $1 in
        --help | -h)
            usage
            exit 0;;
        ## how to invert:  i.e. remove from a Zsh array?
        --ignore | -b)
            ignore_branch=n
            ;;
        # useless:
        --mk-build-deps|  -m)
            build_dependencies=yes
            ;;
        --sign | -s)
            do_sign=y
            ;;
        --nosign | -u)
            # fixme: should use arrays
            # prepend!
            do_sign=n
            ;;
        --pbuilder | -p)
            # /usr/bin/
            GBP_OPTIONS+="--git-builder=git-pbuilder"
            ;;
        --install | -i)
            ## -i don't upgrade, +i don't install at all.
            ## and how to force it? just leave.
            INSTALL_IMMEDIATELY=y
            # fixme: remove the --upgrade
            DPUT_OPTIONS="-i" # not only upgrade!
            ;;
        --keep | -k )
            GBP_OPTIONS+=("--git-no-purge")
            ;;
        --noinstall | -n)
            # INSTALL_IMMEDIATELY=n
            DPUT_OPTIONS="-n"
            ;;
        --verbose | -V )
            GBP_OPTIONS+="--git-verbose"
            ;;
        --version | -v)
            shift
            FORCE=y
            DEFAULT_NEW_VERSION=$1
            ;;
        --distro | -d )
            shift
            USER_DISTRIBUTION=$1
            ;;
        --source| -t )
            # still  dpkg-buildpackage will call dpkg-source --before-build
            # which does not do harm, though.
            build_source=yes
            ;;
        --force | -f )
            FORCE=y
            ;;
        --work | -w )
            GBP_OPTIONS+=(--git-export=WC)
            ;;
        --nocheck )
            DEB_BUILD_OPTIONS+=nocheck
            export DEB_BUILD_OPTIONS
            ;;

        -- )
            shift
            break
    esac
    shift
done

# the rest are options for git-buildpackage

        # ?)
        #     echo "problem: $OPT / $OPTIND:  $ARGS[$OPTIND]"
        #     case $ARGS[$OPTIND] in
        #       --git*)
        #           GBP_OPTIONS+=$ARGS[$OPTIND]
        #           OPTIND=$(expr $OPTIND + 1)
        #           ;;
        #       *)
        #           echo "$OPTIND -> $ARGS[$OPTIND] $OPTARG"
        #           exit 3;;
        #     esac ;;
        # *)
        #     usage
        #     exit 2

if [ $ignore_branch = "y" ];then
    DCH_OPTIONS+=("--ignore-branch")
    GBP_OPTIONS+=("--git-ignore-branch")
fi

if [ $build_source != yes ]; then
    GBP_OPTIONS+=(--git-no-create-orig -b)
fi

if [ $do_sign = "n" ]; then
    GBP_OPTIONS+=(-us -uc)
fi


if [[ $# -gt 0 ]]; then
    dir=$1
    if [[ -d $dir ]]; then
        cd $dir
    else
        usage >&2
        exit 1
        fi
fi
export GITSHA=$(git rev-list --max-count=1 HEAD)

# The changelog is updated inside the Git repo.
# After the git checkout, it will be copied.
if changelog_needs_new_section "snap"
then
    # get the current version & increase. The major maybe.
    if [[ -z ${DEFAULT_NEW_VERSION-} ]]
    then
        load_distr_version_from_changelog

        if [ -n "$USER_DISTRIBUTION" ]; then
            DISTRIBUTION=$USER_DISTRIBUTION
        fi
        increase_version minor

        ( echo -n "Starting a new version "; cecho red -n "$VERSION."
          echo "Could have been explicitely specified with the -v option." ) >&2
    fi

    # This is fishy:  should be added only on git-dch invocation.
    # not _forever_ into the variable!
    DCH_OPTIONS+="--new-version=${DEFAULT_NEW_VERSION:-$VERSION}"

    # Do I have to provide the previous GIT TAG?
    (
        set -x
        gbp dch --auto --snapshot "--debian-tag=$DISTRIBUTION/%(version)s" $DCH_OPTIONS
    )
else
    # cp -v debian/changelog debian/changelog.save
    # Already updated since a release (fixme?). So, the version should be there.
    if [ -n "$USER_DISTRIBUTION" ]; then
        DISTRIBUTION=$USER_DISTRIBUTION
    fi

    (
        set -x
        gbp dch --auto --snapshot $DCH_OPTIONS
    )
fi

# Support for 2 different versions of gbp:
gbp_version=$(gbp buildpackage --version|cut -d ' '  -f 2)
if dpkg --compare-versions $gbp_version gt 0.6; then
    PREVERSION_HOOK_NAME=--git-postexport
else
    PREVERSION_HOOK_NAME=--git-prebuild
fi

cecho red "Starting git-buildpackage, with hooks!"
# --git-sign-tags
# --color=auto
# lsb_release -c


export DPUT_TARGETS

#    DPUT_TARGETS=${MBS_SNAP_TARGETS-${REPREPRO_BASE_DIR+local}}
if [ -n "${REPREPRO_BASE_DIR-}" ]; then
    DPUT_TARGETS=${MBS_SNAP_TARGETS-local}
else
    DPUT_TARGETS=${MBS_SNAP_TARGETS-}
fi

pre_build_hook_args=()
if [[ ${build_dependencies} = 'no' ]] then
   pre_build_hook_args=("-s")
fi

(
set -x
gbp buildpackage \
    --git-ignore-new $GBP_OPTIONS \
    $PREVERSION_HOOK_NAME="pre-build-hook $pre_build_hook_args"\
    --git-cleaner=/bin/true \
    --git-dist=$DISTRIBUTION \
    --git-arch=$(dpkg-architecture -qDEB_BUILD_ARCH) \
    --git-postbuild="dput-install $DPUT_OPTIONS" \
    --git-builder="debuild -eMAKEFLAGS -eGITSHA -eGCC_COLORS -nc --no-check-builddeps"

    # --source-option="--format=\"3.0 (native)\""
)


# snap     fast, without any cow. Doesn't verify dependencies
#          but still  control.in ?
# psnap... using cow-builder
# release
#

# fixme: how to clean after the build? and after a failed one?
