#!/bin/bash

NAME=`date '+arbsrc_%Y_%m_%d__%H_%M.tgz'`

dump_revision() {
    (./SOURCE_TOOLS/build_info.pl 1>&2) && \
      grep ARB_SVN_REVISION ./TEMPLATES/svn_revision.h | \
      perl -ne 'if (/ARB_SVN_REVISION\s+\"(.*)\"/) { $_=$1; s/:/_/; print $_; }'
}

REVISION=`dump_revision`
REVISION_DIR=arbsrc_$REVISION
echo REVISION_DIR=$REVISION_DIR


rm_noerr() {
    test -f $1 && rm -f $1 
}
cleanup() {
    # rm_noerr arbsrc.lst
    rm_noerr arbsrc.lst.tmp
    test -L $REVISION_DIR && rm $REVISION_DIR
    true
}

gen_list() {
    util/arb_srclst.pl $* > arbsrc.lst.tmp || \
        ( \
        echo "Failed to build arbsrc.lst" ; \
        if [ "$*" != "ignore" ] ; then \
        echo "To ignore this error save manually using 'make save2' (only works in SVN checkout)"; \
        fi; \
        false \
        )
}
sort_list() {
    sort < arbsrc.lst.tmp | perl -pne "s/^\./.\/$REVISION_DIR/g;" > arbsrc.lst
}
gen_tarball() {
    ln -s . $REVISION_DIR && \
    tar -zcf $NAME --files-from=arbsrc.lst && \
        ( rm -f arbsrc.tgz ; \
        ln -s $NAME arbsrc.tgz ; \
        true )
}

save() {
    gen_list $* && sort_list && gen_tarball
}

(save $* && cleanup && (ls -alG -rt arbsrc*;true)) || \
(cleanup;echo "Failed to create source tarball";false)
