#!/bin/sh

# Copyright 2017       Luca Bonissi, Brugherio, IT
# Copyright 2009-2012  Eric Hameleers, Eindhoven, NL
# Copyright 2005-2016  Patrick J. Volkerding, Sebeka, Minnesota, USA
# All rights reserved.
#
# Redistribution and use of this script, with or without modification, is
# permitted provided that the following conditions are met:
#
# 1. Redistributions of this script must retain the above copyright
#    notice, this list of conditions and the following disclaimer.
#
#  THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
#  WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
#  MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO
#  EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
#  SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
#  PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
#  OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
#  WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
#  OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
#  ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.


PKGNAM=apache-ant
VERSION=${VERSION:-$(echo $PKGNAM-*.tar.xz | rev | cut -f 2- -d - | cut -f 1 -d - | rev)}
ARCH=java
BUILD=${BUILD:-1}

CWD=$(pwd)
TMP=${TMP:-/tmp}
PKG=$TMP/package-$PKGNAM

rm -rf $PKG
mkdir -p $TMP $PKG

cd $TMP
rm -rf $PKGNAM-$VERSION
tar xvf $CWD/$PKGNAM-$VERSION-bin.tar.xz || exit 1
cd $PKGNAM-$VERSION || exit 1
chown -R root:root .
find . \
  \( -perm 777 -o -perm 775 -o -perm 711 -o -perm 555 -o -perm 511 \) \
  -exec chmod 755 {} \; -o \
  \( -perm 666 -o -perm 664 -o -perm 600 -o -perm 444 -o -perm 440 -o -perm 400 \) \
  -exec chmod 644 {} \;

# Patch for missing Slackware JAVA_HOME variable:
cat $CWD/slackware_gcj_home.diff | patch -p1 --verbose || exit 1

ANT_HOME=/usr/share/ant

# Installing:
mkdir -p $TMP $PKG/usr/share/{ant,java} $PKG/usr/bin
cp -a bin lib etc $PKG/$ANT_HOME/
rm -f $PKG/$ANT_HOME/lib/x*jar

mkdir -p $PKG/etc/profile.d/
cat << EOF > $PKG/etc/profile.d/$PKGNAM.csh
#!/bin/csh
setenv ANT_HOME ${ANT_HOME}
EOF
cat << EOF > $PKG/etc/profile.d/$PKGNAM.sh
#!/bin/sh
export ANT_HOME=${ANT_HOME}
EOF
chmod 0755 $PKG/etc/profile.d/*

cd $PKG/usr/share/java
  for jar in $PKG/$ANT_HOME/lib/*.jar ; do
    ln -s $ANT_HOME/lib/$(basename $jar) $(basename $jar)
  done
cd -

cd $PKG/usr/bin
  ln -s $ANT_HOME/bin/ant
  ln -s $ANT_HOME/bin/antRun
  ln -s $ANT_HOME/bin/antRun.pl
  ln -s $ANT_HOME/bin/runant.pl
  ln -s $ANT_HOME/bin/runant.py
cd -

# Documentation
mkdir -p $PKG/usr/doc/$PKGNAM-$VERSION
for DC in INSTALL KEYS NOTICE README WHATSNEW manual/ ;do
	[ -e $DC ] && cp -r $DC $PKG/usr/doc/$PKGNAM-$VERSION/ || true
done

mkdir -p $PKG/install
cat $CWD/slack-desc > $PKG/install/slack-desc

# Build the package:
cd $PKG
makepkg -l y -c n $TMP/$PKGNAM-$VERSION-$ARCH-$BUILD.txz