#!/bin/bash --

set -e

. /usr/share/javahelper/jh_lib.sh

syntax()
{
   echo -e "Usage: jh_installlibs [options] [jars]"
   echo -e "Options:"
   echo -e "\t-h --help: show this text"
   echo -e "\t-V --version: show the version"
   echo -e "\t-i --indep: act on all Arch: all packages"
   echo -e "\t-s --arch: act on all Arch-specific packages"
   echo -e "\t-p<package> --package=<package>: package to act on (default=all)"  
   echo -e "\t-P<packagedir> --tmpdir=<package>: package directory (default=\$CWD/debian/package)"  
   echo -e "\t-v --verbose: show more information while running"
   echo -e "\t-n --no-act: don't actually do anything, just print the results"
   exit 1
}

ARGS="i indep s arch p package P tmpdir v verbose n no-act" parseargs "$@"

dh_testdir

VERSION="`dpkg-parsechangelog  | sed -n '/^Version:/s/^[^:]*: \(.*\)-[^-]*/\1/p'`"
VERBOSE="`getarg v verbose`"

if [ "$ARGC" != "0" ] ; then
   
   p="`firstpackage`"    

   for (( i=0; i < $ARGC; i++ )); do
      j=${ARGV[i]}
      if [ -n "$VERBOSE" ]; then
         echo "Installing library $j into package $p"
      fi
      mkdir -p debian/$p/usr/share/java
      install -m 644 "$j" "debian/$p/usr/share/java/${j%.jar}-${VERSION}.jar"
      ln -sf ${j%.jar}-${VERSION}.jar "debian/$p/usr/share/java/$j"
   done
   exit 0
fi

for p in `findpackages`; do

   PACKAGEDIR="`getarg P tmpdir`"
   if [ -z "$PACKAGEDIR" ]; then
      PACKAGEDIR="`pwd`/debian/$p"
   else
      PACKAGEDIR=`realpath $PACKAGEDIR`
   fi

   if [ -n "$VERBOSE" ]; then
      echo "Searching $PACKAGEDIR for $p"
   fi

   FILE=
   if [ -f debian/$p.jlibs ]; then
      FILE=debian/$p.jlibs
   elif [ -f debian/jlibs ]; then
      FILE=debian/jlibs
   else
      continue
   fi

   IFS='
'
   for i in `cat "$FILE"`; do
		from="$i"
		to="`basename "$i"`"
      if [ -n "$VERBOSE" ]; then
         echo "Installing library $i into package $p"
      fi
      mkdir -p debian/$p/usr/share/java
      install -m 644 "$from" "debian/$p/usr/share/java/${to%.jar}-${VERSION}.jar"
      ln -sf ${to%.jar}-${VERSION}.jar "debian/$p/usr/share/java/$to"
   done

   unset PACKAGEDIR

done

