#!/bin/sh 
set -e 

update=1
sources=0
changes=1
arch=`dpkg-architecture -qDEB_BUILD_ARCH`
cvsroot=":pserver:cvs@root.cern.ch:/user/cvs"
svnroot="https://root.cern.ch/svn/root/"
version=
clean=1
debug=0
lintian=1
build=1
orig_only=0
workdir=
srcdir=
tag=
branch=
savdir=`pwd`
scrdir=
sign=1
pbuild=0

# ____________________________________________________________________
message()
{
    opt=
    post=
    while test $# -gt 0 ; do 
        case $1 in 
            -n) post=" ..." ; opt="$opt $1" ;;
            -*) opt="$opt $1" ;; 
            *)  break;;
        esac
        shift
    done
    echo $opt "$@${post}"
}

# ____________________________________________________________________
check_retval()
{
    retval=$?
    if test $# -gt 0 ; then 
        message -n $@ ":"
    fi
    if test $retval -ne 0 ; then 
        echo " Failure"
        cd $savdir
        exit $retval
    else
        echo " OK"
    fi
}

# ____________________________________________________________________
get_original()
{
    # if test -f $orig && test ! -d ${origdir}; then 
    #   echo -n "Extracting existing orig file ... "
    #   tar -xzf ${orig}
    #   echo "done" 
    # fi
    if test -f ${orig} && test $sources -eq 0 ; then 
        message -n "Using existing source tar-ball ${orig}" 
        check_retval
        return 0
    fi
    if test ! -d ${origdir} ; then 
        message -n "Getting original sources w/tag=$tag, w/branch=$branch"
        if test "x$tag" != "x" ; then 
            cmd="co" 
            dir="tags/${tag}"
        elif test "x$branch" != "x" ; then
            cmd="co" 
            dir="branches/${branch}"
        else
            cmd="co" 
            dir="trunk"
        fi
        # cvs -qd $cvsroot $cmd -d ${origdir}  root > orig-${version}.log
        svn co $svnroot/$dir ${origdir} > $workdir/orig-${version}.log 2>&1
        check_retval
    fi
    if test ${origdir} -nt ${orig} || test $sources -gt 0 ; then 
        cd ${origdir}
        if test $update -gt 0 ; then 
            message "Updating original sources (`pwd`)"
            ${scrdir}/changes.sh --verbose --update-only --srcdir ${srcdir} \
                >> $workdir/orig-${version}.log 2>&1
        else
            message "Preparing directory $origdir"
            ./build/package/lib/makedebdir.sh --no-setup --purge
                >> $workdir/orig-${version}.log 2>&1 
        fi
        check_retval "Update original sources"
        cd ..  
        message -n "Creating tar-ball"
        #cp extra/s050000l.p* ${origdir}/build/package/common/
        #cp extra/root-system-bin.png ${origdir}/build/package/debian/
        tar --exclude=CVS               \
            --exclude=.cvsignore        \
            --exclude=.svn              \
            -czf ${orig} ${origdir}
        check_retval
    fi
}

# ____________________________________________________________________
prep_sources()
{
    rm -f                                       \
        io/xml/inc/TXMLEngine.h                 \
        io/xml/src/TXMLEngine.cxx               
    #   proof/proofplayer/inc/TFileMerger.h     \
    #   proof/proofplayer/src/TFileMerger.cxx   
    #   proof/proofplayer/inc/TFileMerger.h     \
    #   proof/proofplayer/src/TFileMerger.cxx   
    #   geom/geompainter/inc/TGeoOverlap.h      \
    #   geom/geompainter/src/TGeoOverlap.cxx    \
    rm -f                                       \
        math/unuran/src/.bogus.tar.gz           
    rm -rf htmldoc

    copts=""
    if test $update  -gt 0 ; then copts="$opts --update"  ; fi 
    if test $changes -gt 0 ; then copts="$opts --changes" ; fi 
    message "Preparing sources ($copts)"
    if test "x$copts" != "x" ; then 
        ${scrdir}/changes.sh ${revision} --verbose ${copts}
    else
        ./build/package/lib/makedebdir.sh --purge --no-setup --leave-old        
    fi
    check_retval "Preparing sources"

    message "Running prep script ..."
    ./build/package/lib/makedebdir.sh --clean
    check_retval "Running prep script"

    for p in ${scrdir}/extra/*.patch ; do 
        if test ! -f $p ; then continue ; fi
        message -n "Applying patch $p" 
        patch -d. -p1 < $p 
        check_retval 
    done

    rm -f debian/control
    message "Making control file ..."
    fakeroot debian/rules debian/control
    check_retval "Making control file"
}

# ____________________________________________________________________
build_package()
{
    message "Now building"
    opt="-i"
    if test $pbuild -lt 1 ; then opt="$opt -rfakeroot" ; fi
    if test $clean  -lt 1 ; then opt="$opt -nc" ;        fi
    if test $pbuild -lt 1 ; then opt="$opt -ICVS";       fi
    if test $sign   -lt 1 ; then opt="$opt -us -uc" ;    fi
    if test $nobin  -gt 0 ; then opt="$opt -S" ;         fi
    if test $debug  -gt 0 ; then 
        export DEB_BUILD_OPTIONS="debug nostrip noopt"
    fi
    cmd=dpkg-buildpackage
    lognam=build
    if test $pbuild -gt 0 ; then 
        opt="--debbuildopts \"$opt\""
        cmd=pdebuild
        lognam=pbuild
    fi
    echo $cmd $opt
    $cmd ${opt}  2> /dev/stdout | \
        tee ${workdir}/${lognam}-${version}-${revision}.log 
    check_retval "Building package"
    cd ../
    if test $lintian -gt 0 && test $pbuild -lt 1; then
        lintian -i root-system_${version}-${revision}_${arch}.changes \
            2> /dev/stdout | tee ${workdir}/lintian_${version}-${revision}.log 
    fi
}

# ____________________________________________________________________
usage()
{
    cat <<EOF
Usage: $0 [OPTIONS]

Options:
        -h,--help       Show this help 

        -b,--no-build   Do not build the packages, just prepare
        -u,--no-update  Do not run the updates 
        -c,--no-changes Do not make changes
        -s,--sources    Force remake of source tar-ball
        -P,--source-pkg Only generate a source package 
        -o,--orig-only  Only make the orig tar-ball

        -n,--no-clean   Do not clean Debian directory 
        -g,--no-sign    Do not sign packages
        -p,--pbuilder   Use pbuilder (clean-room chroot build)

        -d,--debug      Build debug packages
        -l,--lint       Run lintian on the packages
        -S,--source-dir Set the source directory
        -w,--workdir    Set the working directory
EOF
    exit 0
}

# ____________________________________________________________________
while test $# -gt 0 ; do 
    case $1 in 
        -h|--help)       usage          ;; 
        -u|--no-update)  update=0;      ;; 
        -c|--no-changes) changes=0      ;; 
        -s|--sources)    sources=1      ;;
        -n|--no-clean)   clean=0        ;;
        -b|--no-build)   build=0        ;;
        -d|--debug)      debug=1        ;;
        -l|--lint)       lintian=1      ;;
        -o|--orig-only)  orig_only=1    ;; 
        -S|--source-dir) srcdir=$2      ; shift ;; 
        -g|--no-sign)    sign=0         ;;
        -w|--workdir)    workdir=$2     ; shift ;;
        -B|--scriptdir)  scrdir=$2      ; shift ;; 
        -p|--pbuilder)   pbuild=1 ; lintian=0  ;;
        -P|--source-pkg) nobin=1  ; lintian=0 ; pbuild=0 ;;
        *)               version=$1     ;;
    esac
    shift
done

# ____________________________________________________________________
if test "x$workdir" = "x" ; then 
    workdir=`pwd`
    workdir=`dirname $workdir`
fi
if test "x$srcdir" = "x" ; then 
    srcdir=$workdir/root
fi
if test "x$scrdir" = "x" ; then 
    scrdir=`dirname $0`
fi



# ____________________________________________________________________
savdir=`pwd`
if test ! -d ${srcdir} ; then 
    echo "Directory ${srcdir} not found" 
    exit 2;
fi
message -n "Getting the version number ... "
version=`cat ${srcdir}/build/version_number | tr '/' '.'` 
case $version in 
    *.*.00*) branch="v`echo $version | sed 's,[./],-,'g`-patches" ;;
    *)
esac
version=`echo $version | sed 's/\([0-9.]*\).*/\1/'` 
orig=root-system_${version}.orig.tar.gz
origdir=root-system-${version}.orig
check_retval "$version"

# ____________________________________________________________________
message -n "Getting the revision number ..."
revision=`head -n 1 ${srcdir}/build/package/debian/changelog | sed "s/root-system (${version}-\([0-9][-0-9]*\)).*/\1/"` 
# echo "Version: $version Revision: $revision"
check_retval $revision

cd ${workdir}
get_original

if test $orig_only -gt 0 ; then 
    exit 0
fi
# ____________________________________________________________________
message "Changing directory to ${srcdir}"
cd ${srcdir}

prep_sources
if test $build -gt 0 ; then
    build_package
fi

cd ${savdir}
# ____________________________________________________________________
#
# EOF
#