#!/bin/sh
# Heavily based on the Slackware 12.2 SlackBuild

CWD=`pwd`
NAME0=imagej
NAME=ImageJ
VERSION=1.41
NAME1=ij141-x86
TARGET=i486
BUILD=1lu
ARCH=${ARCH:-i486}
EXT=tar.gz
SOURCE=http://rsb.info.nih.gov/ij/download/linux/$NAME1.$EXT

if [ ! -e $NAME1.$EXT ]; then
wget -c $SOURCE
fi

if [ "$TMP" = "" ]; then
  TMP=/tmp
fi
PKG=$TMP/package-$NAME

if [ "$EXT" = "tar.gz" ]; then
   TARCMD="tar xvzf"
elif [ "$EXT" = "tgz" ]; then
   TARCMD="tar xvzf"
elif [ "$EXT" = "tar.bz2" ]; then
   TARCMD="tar xvjf"
elif ["$EXT" = "gz" ]; then
   TARCMD="gunzip"
elif ["$EXT" = "zip" ]; then
   TARCMD="gzip"
fi

if [ ! -d $TMP ]; then
  mkdir -p $TMP # location to build the source
fi
if [ ! -d $PKG ]; then
  mkdir -p $PKG # place for the package to be built
fi

echo "+================+"
echo "| $NAME-$VERSION |"
echo "+================+"

cd $TMP
$TARCMD $CWD/$NAME1.$EXT
cd $NAME
chown -R root:root .
find . -perm 666 -exec chmod 644 {} \;
find . -perm 664 -exec chmod 644 {} \;

mkdir -p $PKG/usr/share/$NAME
mkdir -p $PKG/usr/bin
mkdir -p $PKG/usr/doc/$NAME-$VERSION

cp -r $TMP/$NAME/* $PKG/usr/share/$NAME
mv $PKG/usr/share/$NAME/README.html $PKG/usr/doc/$NAME-$VERSION

mv $PKG/usr/share/$NAME/run /$PKG/usr/bin/ImageJ
rm -rf $PKG/usr/share/$NAME/jre
chmod 755 $PKG/usr/bin/*
chmod -R 755 $PKG/usr/share/*

sed -i "s|./jre/bin/||g" $PKG/usr/bin/$NAME
sed -i "s|ij.jar|/usr/share/ImageJ/ij.jar|g" $PKG/usr/bin/$NAME
mkdir -p $PKG/install
cat $CWD/slack-desc > $PKG/install/slack-desc
cat $CWD/slack-desc > $PKG/usr/doc/$NAME-$VERSION/slack-desc
cat $CWD/$NAME0.SlackBuild > $PKG/usr/doc/$NAME-$VERSION/$NAME0.SlackBuild
chown -R root:root $PKG/usr/doc/$NAME-$VERSION

cd $PKG
requiredbuilder -v -y -s $CWD $PKG
makepkg -l y -c n $CWD/$NAME0-$VERSION-$ARCH-$BUILD.tgz

if [ "$1" = "--cleanup" ]; then
  rm -rf $TMP/$NAME-$VERSION
  rm -rf $PKG
fi
