#!/bin/sh


# NOTE: $(dirname $0) is read-only, use space under $TARGET_ROOT
JAVA_LOCATION=${JAVA_TARGET_LOCATION:-"/usr/java"}
JAVA_NAME="oracle-jdk"
JAVA_HOME=$JAVA_LOCATION/$JAVA_NAME
JAVA_DOWNLOAD_URL=${JAVA_DOWNLOAD_URL:-"http://download.oracle.com/otn-pub/java/jdk/7u51-b13/jdk-7u51-linux-x64.tar.gz"}

if [ ! -d $JAVA_LOCATION ]; then
    if [ $test_only -eq 0 ]; then
        echo "Begin: installation of Java"
        mkdir -p $JAVA_LOCATION

        if [ -n "$JAVA_DOWNLOAD_URL" ]; then
            JAVA_FILE=$(basename $JAVA_DOWNLOAD_URL)
            wget --no-check-certificate --no-cookies -c \
                --header "Cookie: gpw_e24=http%3A%2F%2Fwww.oracle.com%2F; oraclelicense=accept-securebackup-cookie" \
                -O $JAVA_LOCATION/$JAVA_FILE $JAVA_DOWNLOAD_URL
        elif [ -n "$JAVA_FILE" ]; then
            install -D -g root -o root -m 0755 $(dirname $0)/$JAVA_FILE $JAVA_LOCATION
        fi

        cd $JAVA_LOCATION

        echo "Decompressing Java archive"
        printf "\n\n" | tar -zxf $JAVA_FILE
        echo "Setting up $JAVA_NAME"
        chown -R root:root $JAVA_LOCATION
        JAVA_DIR=`ls -1 $JAVA_LOCATION | grep -v tar.gz`
        ln -s $JAVA_LOCATION/$JAVA_DIR $JAVA_HOME

        setup-java-home $JAVA_HOME $JAVA_HOME

        rm $JAVA_FILE

        echo "End: installation of Java"
    else
        exit 0
    fi
fi
