#!/bin/bash
#set -x

if [ "$EUID" -ne 0 ]
  then echo "Please run this script as root"
  exit 1
fi


if ! [ -d /srv/hops/hadoop-3.2.0.2-EE-RC0 ]
then
   echo "This patch only works with hopsworks 2.1 that uses hadoop-3.2.0.2-EE-RC0"
   exit 1
fi

cd /srv/hops/hadoop/


#clean up if the script is run again
rm -f hopsfs-2.1-fix.tar
rm -rf share.bak

wget https://repo.hops.works/master/hopsfs-2.1-fix.tar

echo "Stopping services"
if systemctl --all --type service | grep -q "namenode";then
   systemctl stop namenode
fi

if systemctl --all --type service | grep -q "datanode";then
   systemctl stop datanode
fi

echo "Copying files"
mv share share.bak
tar xf hopsfs-2.1-fix.tar

if [ -d /srv/hops/ndb-hops ]
then
  cp /srv/hops/ndb-hops/ndb-dal.jar ./share/hadoop/common/lib/ndb-dal.jar
fi

if [ -f share.bak/hadoop/common/lib/jmx_prometheus_javaagent-0.12.0.jar ]
then
  cp share.bak/hadoop/common/lib/jmx_prometheus_javaagent-0.12.0.jar share/hadoop/common/lib/jmx_prometheus_javaagent-0.12.0.jar
fi

if [ -f share.bak/hadoop/yarn/lib/spark-2.4.3.2-yarn-shuffle.jar ]
then
  cp share.bak/hadoop/yarn/lib/spark-2.4.3.2-yarn-shuffle.jar share/hadoop/yarn/lib/spark-2.4.3.2-yarn-shuffle.jar
fi

chown hdfs:hadoop share -R

echo "Starting services"
if systemctl --all --type service | grep -q "namenode";then
   systemctl start namenode
fi

if systemctl --all --type service | grep -q "datanode";then
   systemctl start datanode
fi

echo "Done"
