#! /bin/bash

# http://software.broadinstitute.org/software/igv/

## https://data.broadinstitute.org/igv/projects/downloads/2.9/IGV_2.9.2.zip
## https://data.broadinstitute.org/igv/projects/downloads/2.9/IGV_Linux_2.9.2_WithJava.zip

set -xe

PKG=igv
VERSION=2.9.2
VERSION2=$(echo $VERSION | cut -d. -f1,2)
BUILD=0

PREFIX=/pkg/$PKG-$VERSION-$BUILD
if [ -n "$TESTING" ]; then PREFIX=/dev/shm/$PKG-$VERSION-$BUILD ; fi

mkdir -p $PREFIX
cat >$PREFIX/profile <<-EOF
	. /pkg/openjdk-11.0.3.2-0/profile
	PATH=$PREFIX:\$PATH
	if [ -d $PREFIX/.compatlibs ]; then export LD_LIBRARY_PATH=$PREFIX/.compatlibs\${LD_LIBRARY_PATH:+:}\$LD_LIBRARY_PATH ; fi
EOF
. $PREFIX/profile

BUILDDIR=$PREFIX/build

mkdir -p $BUILDDIR
cd $BUILDDIR

# orig: https://data.broadinstitute.org/igv/projects/downloads/2.9/IGV_2.9.2.zip
BEEHIVE=https://beehive.molgen.mpg.de/e3824c72c2e0bd5c9616ec8888028e41/IGV_2.9.2.zip
test -e IGV_$VERSION.zip || wget -nv $BEEHIVE
test -d IGV_$VERSION || unzip -q IGV_$VERSION.zip


find . -perm 775 -exec chmod 755 {} \+ -o -perm 664 -exec chmod 644 {} \+
sed -e '/^exec/ s/Xmx4g/Xmx${IGVXMX:-8g}/' -i IGV_$VERSION/igv.sh
sed -e '/^exec/ s/Xmx4g/Xmx${IGVXMX:-8g}/' -i IGV_$VERSION/igv_hidpi.sh

mv IGV_$VERSION/* $PREFIX
rmdir IGV_$VERSION

cd $PREFIX
cat >igv <<-'EOF'
	#!/bin/sh
	
	die() { echo $1; exit 1; }
	
	parse_mem() {
	  case $1 in
	    [1-9]g | [1-9][0-9]g | [1-2][0-9][0-9]g)
	      IGVXMX=$1 ;;
	    *)
	      die "# Error: need a proper value for memory to use, eg. 8g" ;;
	  esac
	}
	
	script=`basename $0`
	
	IGVXMX=${IGVXMX:-8g}
	export IGVXMX
	
	case "$script" in
	  igvxmem_hidpi)
	     parse_mem $1; shift
	     exec igv_hidpi.sh "$@" ;;
	  igvxmem)
	     parse_mem $1; shift
	     exec igv.sh "$@" ;;
	esac
	
	MEM_KB=$(grep -m1 'MemTotal:' /proc/meminfo | rev | cut -d' ' -f2 | rev)
	MEM_GB=$(( $MEM_KB/1024/1024 ))
	
	CONSIDER="#   Consider using 'igvxmem XYZg' to start igv with proper memory setup."
	
	if test $MEM_GB -lt 7; then
	  MSG="#   This is fairly below the suitable amount of 8 GB.\n$CONSIDER"
	elif test $MEM_GB -gt 17 ; then
	  MSG="$CONSIDER\n#   To gain better performance you may increase the memory in sane steps."
	fi
	
	if test -n "$MSG"; then
	  echo '# NOTE:'
	  echo "#   found approx. $MEM_GB GB of Memory on your host."
	  echo '#'
	  echo -e "$MSG"
	  echo '#'
	  echo '# igv with default settings will start in 3 seconds ...'
	  sleep 3
	fi
	
	case "$script" in
	  igv_hidpi)
	     exec igv_hidpi.sh "$@" ;;
	  *)
	     exec igv.sh "$@" ;;
	esac
	
EOF

chmod 755 igv

ln -s igv igvxmem
ln -s igv igv_hidpi
ln -s igv igvxmem_hidpi


exit