#! /bin/bash

INSTALL_DIR=/usr/hdp/current/incubator-zeppelin

ZEPPELIN_BINARIES_LINK=https://dl.dropboxusercontent.com/u/114020/zeppelin-snapshots/spark-1.5.1TP-HDP2.3.2/zeppelin-0.5.5-incubating-spark151-tp.tar.gz

installZeppelind() {
echo "Adding Zeppelin's Init.d configuration"

cat >/etc/init.d/zeppelind <<EOL
test -e $INSTALL_DIR/bin/zeppelin-daemon.sh || exit 1
sudo $INSTALL_DIR/bin/zeppelin-daemon.sh \$@
EOL

chmod +x /etc/init.d/zeppelind
update-rc.d zeppelind defaults
update-rc.d zeppelind enable
}

# Import the helper method module.
wget -O /tmp/HDInsightUtilities-v01.sh -q https://hdiconfigactions.blob.core.windows.net/linuxconfigactionmodulev01/HDInsightUtilities-v01.sh && source /tmp/HDInsightUtilities-v01.sh && rm -f /tmp/HDInsightUtilities-v01.sh

fullHostName=$(hostname -f)
echo "fullHostName=$fullHostName"
if [[ $fullHostName != headnode0* && $fullHostName != hn0* ]]; then
    echo "$fullHostName is not headnode 0. This script has to be run on headnode 0."
    exit 0
fi

# In case Zeppelin is installed, exit.
if [ -e $INSTALL_DIR ]; then
    echo "Zeppelin is already installed, exiting ..."
    exit 0
fi

echo download_file $ZEPPELIN_BINARIES_LINK /tmp/zeppelin-0.5.5-incubating-SNAPSHOT.tar.gz
download_file $ZEPPELIN_BINARIES_LINK /tmp/zeppelin-0.5.5-incubating-SNAPSHOT.tar.gz

if [ ! -f /tmp/zeppelin-0.5.5-incubating-SNAPSHOT.tar.gz ]; then
    echo "Failed to download Zeppelin binaries. Exiting..."
    exit 1
fi

echo untar_file /tmp/zeppelin-0.5.5-incubating-SNAPSHOT.tar.gz /usr/hdp/current
untar_file /tmp/zeppelin-0.5.5-incubating-SNAPSHOT.tar.gz /usr/hdp/current

echo mv /usr/hdp/current/zeppelin-*-incubating-SNAPSHOT $INSTALL_DIR
mv /usr/hdp/current/zeppelin-*-incubating-SNAPSHOT $INSTALL_DIR

# remove the temporary file
rm -f /tmp/zeppelin-0.5.5-incubating-SNAPSHOT.tar.gz

if ls $INSTALL_DIR/interpreter/spark/dep/zeppelin-spark-*.jar 
then
    export LOCAL_SPARK_JAR=$INSTALL_DIR/interpreter/spark/dep/zeppelin-spark-*.jar
else
    export LOCAL_SPARK_JAR=$INSTALL_DIR/interpreter/spark/zeppelin-spark-*.jar
fi
echo "LOCAL_SPARK_JAR is $LOCAL_SPARK_JAR"

SPARK_JAR_DIR=wasb:///apps/zeppelin/
SPARK_JAR=$SPARK_JAR_DIR/zeppelin-spark-0.5.5-SNAPSHOT.jar
hadoop fs -mkdir -p $SPARK_JAR_DIR
hadoop fs -put -f -p $LOCAL_SPARK_JAR $SPARK_JAR

download_file https://hdiconfigactions.blob.core.windows.net/linuxincubatorzeppelinv01/zeppelin-env.sh $INSTALL_DIR/conf/zeppelin-env.sh

installZeppelind
service zeppelind start
echo "Installation succeeded"