#!/bin/bash -ex

DOWNLOAD_DIR=/tmp
APPLICATION_DIR=/home/apache/presto
PRESTO_DIR=presto-server-0.201
MASTER_IP=$(grep node-master2- /etc/hosts | awk '{print $1}')
if [ -z "$MASTER_IP" ]; then
    MASTER_IP=$(grep node-master1- /etc/hosts | awk '{print $1}')
fi

# get node type
if [ $# != 1 ]; then
    echo "Need TYPE argument. The valide TYPE is [ coordinator | worker | dualroles ]"
    return 1
else
    if [ "$1" = "dualroles" ] || [ "$1" = "coordinator" ] || [ "$1" = "worker" ]; then
        TYPE=$1
    else
        echo "Invalid TYPE : $1. The valide TYPE is [ coordinator | worker | dualroles ]"
        return 1
    fi
fi

echo "=====================Set env==================================="
source /opt/client/bigdata_env

echo "=====================Download package=========================="
cd $DOWNLOAD_DIR
curl -O https://mrs-samples-bootstrap-cn-north-1.obs.cn-north-1.myhwclouds.com/presto/$PRESTO_DIR.tar.gz
curl -O https://mrs-samples-bootstrap-cn-north-1.obs.cn-north-1.myhwclouds.com/presto/$TYPE.etc.tar.gz

echo "=====================Install Presto============================"
mkdir -p $APPLICATION_DIR
cd $APPLICATION_DIR
mkdir -p data
chmod 755 data
tar -zxvf  $DOWNLOAD_DIR/$PRESTO_DIR.tar.gz

echo "=====================Configure Presto=========================="
cd $APPLICATION_DIR/$PRESTO_DIR
tar -zxvf $DOWNLOAD_DIR/$TYPE.etc.tar.gz
sed -i "s/ffffffff-ffff-ffff-ffff-ffffffffffff/$(uuidgen)/"  etc/node.properties
if [ "$1" = "worker" ]; then
    sed -i "s/localhost/$MASTER_IP/"  etc/config.properties
fi

echo "=====================Start the Presto daemon==================="
bin/launcher start
