#!/bin/sh -x

HOME=/home/$USER
SHARED=$HOME/shared/asy
ASYMPTOTE=$HOME/asymptote
BUILD=/usr/local/src

MAKEFLAGS=-j8
export MAKEFLAGS

BINDIR=usr
test /usr -ef $BUILD/$BINDIR && exit
LATEXDIR=$BUILD/$BINDIR/share/texmf/tex/latex/asymptote
cd $BUILD
rm -rf asymptote
git clone https://github.com/vectorgraphics/asymptote
cd asymptote
git log > ChangeLog
VERSIONgit=`grep AC_INIT configure.ac | cut -s -d[ -f3 | cut -s -d] -f1`
VERSION=${VERSIONgit/git/}$1
cat configure.ac | sed -e "s/$VERSIONgit/$VERSION/" > configure.ac_
mv configure.ac_ configure.ac
cat $ASYMPTOTE/asymptote.spec | sed -e "s|Version:.*|Version:        $VERSION|" > asymptote.spec
SRC=asymptote-$VERSION.src.tgz
cp asymptote.spec $ASYMPTOTE
cd $BUILD
rm -rf asymptote-$VERSION
rm -rf $BUILD/$BINDIR
mv asymptote asymptote-$VERSION
chown -R root:root asymptote-$VERSION
cd asymptote-$VERSION
find . -name ".[^.]*" -exec rm -rf {} \;
./autogen.sh
./configure
make $MAKEFLAGS check || exit
make uninstall
build-scripts/build-asygl
make $MAKEFLAGS asy
rm base/webgl/asygl-*.js
make -j1 all
make -j1 install
strip asy
rm -rf webgl/node_modules
make DESTDIR="$BUILD/" latexdir=$LATEXDIR install
rm $BUILD/$BINDIR/local/info/dir
cp -a $BUILD/asymptote-$VERSION/ChangeLog .
cp -a $ASYMPTOTE/ReleaseNotes .
rm -rf $SHARED/asydoc
mkdir -p $SHARED/asydoc/png
mkdir -p $SHARED/asydoc/FAQ
cp -a $BUILD/asymptote-$VERSION/doc/asymptote.sty $SHARED/asydoc
make distclean
cd /usr/local/share/doc/asymptote
cp -a *.pdf ../../man/man1/asy.1 ../../asymptote/asy-keywords.el $SHARED/asydoc
cp -a /usr/local/share/info/asymptote/asymptote.info $SHARED/asydoc/png
cp -a /usr/local/share/info/asy-faq.info $SHARED/asydoc/FAQ
cd $BUILD
tar cfz $SRC asymptote-$VERSION
tar cfz asymptote-$VERSION.x86_64.tgz $BINDIR
cp $SRC $SHARED
rm -rf $BUILD/$BINDIR
tar -zxf asymptote-$VERSION.x86_64.tgz
su rpmbuild -c "rpmbuild -ta --nodeps $SRC && rm -rf ~/rpms/BUILD/asymptote-$VERSION&&chmod -R g+r /u/rpmbuild/rpms/RPMS/"
