#!/bin/bash
#
# checkin.sh
#
# This script automates generation of a new overlay tarball from a
# git clone or repo+branch combination for the "keepalived" image in OBS.
#

#set -x

BASEDIR=$(pwd)

EXISTING=""
REPO="https://github.com/umich-arc/keepalived.git"
BRANCH="1.2.2"
OVERLAY="root.tar.gz"

function usage {
    set +x
    echo "Usage:"
    echo "  ${0} [-h,--help] [-e,--existing CLONE]"
    echo "             [-r,--repo REPO] [-b,--branch BRANCH]"
    echo ""
    echo "Options:"
    echo "    --existing  Use existing git clone CLONE"
    echo "    --repo      Make a fresh clone of git repo REPO"
    echo "    --branch    Use branch BRANCH with fresh clone"
    echo ""
    echo "Notes:"
    echo "    If existing clone is given, repo and branch are ignored."
    echo "    Repo defaults to $REPO"
    echo "    Branch defaults to $BRANCH"
    exit 1
}

function _error_exit {
    echo >&2 $1
    exit $2
}

function _verify_git_describe {
    git describe --tags
    echo "Does this version number looks sane? y/[N]"
    read a
    if [ "x$a" != "xy" ] ; then
        _error_exit "Aborting!" 1
    fi
}

GETOPT=$(getopt -o b:e:hr: --long "branch:,existing:,help,repo:" \
       -n 'checkin.sh' -- "$@")
test "$?" -eq 0 || _error_exit "Terminating..." 1
eval set -- "$GETOPT"

while true ; do
    case "$1" in
        -b|--branch)      BRANCH="$2"   ; shift 2 ;;
        -e|--existing) EXISTING="$2" ; shift 2 ;;
        -h|--help)     usage ;; # does not return
        -r|--repo)     REPO="$2"     ; shift 2 ;;
        --) shift ; break ;;
        *) echo "Internal error" ; exit 1 ;;
    esac
done

if [ -n "$EXISTING" ] ; then
    if [ ! -d "$EXISTING" ] ; then
        _error_exit "Alleged directory ->$EXISTING<- is not a directory" 1
    fi
    if [ ! -r "$EXISTING" ] ; then
        _error_exit "I cannot read directory ->$EXISTING<-" 1
    fi
    if [ ! -w "$EXISTING" ] ; then
        _error_exit "I cannot write to directory ->$EXISTING<-" 1
    fi
    if [ ! -x "$EXISTING" ] ; then
        _error_exit "I cannot cd to directory ->$EXISTING<-" 1
    fi
    CLONE="$EXISTING"
else
    echo "Will make fresh clone of repo ->$REPO<- branch ->$BRANCH<-"
    # TMPDIR=$(mktemp -d --tmpdir=$BASEDIR)  # does not work due to http://tracker.ceph.com/issues/39556
    TMPDIR=$(mktemp -d)
    echo "Created temporary temporary $TMPDIR"
    git clone --progress --branch $BRANCH $REPO $TMPDIR
    CLONE="$TMPDIR"
fi

pushd $CLONE
_verify_git_describe
popd

echo "Creating new tarball from $CLONE"
tar -C $CLONE/skel -czvf $OVERLAY .

if [ -n "$TMPDIR" ] ; then
    echo "Nuking the clone"
    rm -rf $TMPDIR
fi

echo "Done! Run \"osc ci --noservice\" to commit."
