#!/usr/bin/env bash

## diagnostics

function fail()
{
  echo "$1" >&2
  exit 2
}


## parameters

VERSION="7u72"
FULL_VERSION="1.7.0_72"

ARCHIVE_LINUX32="jdk-${VERSION}-linux-i586.tar.gz"
ARCHIVE_LINUX64="jdk-${VERSION}-linux-x64.tar.gz"
ARCHIVE_DARWIN="jdk${FULL_VERSION}.jdk.tar.gz"
ARCHIVE_WINDOWS="jdk${FULL_VERSION}.tar.gz"


## main

DIR="jdk-${VERSION}"
mkdir "$DIR" || fail "Cannot create fresh directory: \"$DIR\""


# README

cat >> "$DIR/README" << EOF
This is JDK/JRE $FULL_VERSION as required for Isabelle.

See http://www.oracle.com/technetwork/java/javase/downloads/index.html
for the original downloads, which are covered by the Oracle Binary
Code License Agreement for Java SE.

Linux, Mac OS X, Windows work uniformly, depending on certain
platform-specific subdirectories.
EOF


# settings

mkdir "$DIR/etc"
cat >> "$DIR/etc/settings" << EOF
# -*- shell-script -*- :mode=shellscript:

case "\${ISABELLE_PLATFORM64:-\$ISABELLE_PLATFORM32}" in
  x86-darwin)
    echo "### Java unavailable on 32bit Macintosh!" >&2
    ;;
  x86_64-darwin)
    ISABELLE_JDK_HOME="\$COMPONENT/\$ISABELLE_PLATFORM64/Contents/Home"
    ;;
  *)
    ISABELLE_JDK_HOME="\$COMPONENT/\${ISABELLE_PLATFORM64:-\$ISABELLE_PLATFORM32}"
    ;;
esac
EOF


# content

#GNU tar (notably on Mac OS X)
if [ -x /usr/bin/gnutar ]; then
  function tar() { /usr/bin/gnutar "$@"; }
fi

mkdir "$DIR/x86-linux" "$DIR/x86_64-linux" "$DIR/x86_64-darwin" "$DIR/x86-cygwin"

tar -C "$DIR/x86-linux" -xf "$ARCHIVE_LINUX32"
tar -C "$DIR/x86_64-linux" -xf "$ARCHIVE_LINUX64"
tar -C "$DIR/x86_64-darwin" -xf "$ARCHIVE_DARWIN"
tar -C "$DIR/x86-cygwin" -xf "$ARCHIVE_WINDOWS"

(
  cd "$DIR"
  for PLATFORM in x86-linux x86_64-linux x86-cygwin
  do
    mv "$PLATFORM/jdk${FULL_VERSION}"/* "$PLATFORM"/.
    rmdir "$PLATFORM/jdk${FULL_VERSION}"
  done
  PLATFORM=x86_64-darwin
  mv "$PLATFORM/jdk${FULL_VERSION}.jdk"/* "$PLATFORM"/.
  rmdir "$PLATFORM/jdk${FULL_VERSION}.jdk"
)

chgrp -R isabelle "$DIR"
chmod -R a+r "$DIR"
chmod -R a+X "$DIR"

find "$DIR/x86_64-darwin" -name "._*" -exec rm -f {} ";"

echo "Sharing ..."
(
  cd "$DIR/x86-linux"
  for FILE in $(find . -type f)
  do
    for OTHER in \
      "../x86_64-linux/$FILE" \
      "../x86_64-darwin/Contents/Home/$FILE" \
      "../x86-cygwin/$FILE"
    do
      if cmp -s "$FILE" "$OTHER"
      then
        echo -n "*"
        ln -f "$FILE" "$OTHER"
      fi
    done
  done
)
echo


# create archive

echo "Archiving ..."
tar -c -z -f "${DIR}.tar.gz" "$DIR" && echo "${DIR}.tar.gz"
