#!/bin/bash
#
# SkyForm AIP Spark Cluster launcher script
# Copyright 2019 Skycloud Software
#
#
if [ "_$SPARK_HOME" == "_" ]; then
    echo "Environment SPARK_HOME is not set"
    exit 1
fi

if [ "_$CB_TASK_COMPONENT" == "_" ]; then
    echo "Not running as a SkyForm AIP Spark job"
    exit 1
fi

. "${SPARK_HOME}/sbin/spark-config.sh"

. "${SPARK_HOME}/bin/load-spark-env.sh"

export SPARK_LOG_DIR=$HOME/.spark
if [ ! -d $SPARK_LOG_DIR ]; then
    mkdir $SPARK_LOG_DIR
fi
export SPARK_PID_DIR=$SPARK_LOG_DIR
export SPARK_WORKER_DIR=$SPARK_LOG_DIR
export SPARK_NO_DAEMONIZE=y

export SPARK_WORKER_CORES=1
memlimit=`ulimit -m`
if [ $memlimit != "unlimited" ]; then
    export SPARK_WORKER_MEMORY=$((memlimit/1000))M
fi

case $CB_TASK_COMPONENT in
    master)
        "${SPARK_HOME}/sbin"/spark-daemon.sh start org.apache.spark.deploy.master.Master \
        $CB_JOBID --host $HOSTNAME --port $SPARK_MASTER_PORT \
        --webui-port $SPARK_MASTER_WEBUI_PORT
        ;;
    worker)
        "${SPARK_HOME}/sbin"/spark-daemon.sh start org.apache.spark.deploy.worker.Worker \
        ${CB_JOBID}-${RANK} --port $SPARK_WORKER_PORT --webui-port $SPARK_WORKER_WEBUI_PORT \
        $MASTER_URL
        ;;
    client)
        sleep 10
        "${SPARK_HOME}/bin"/`basename $0` --master $MASTER_URL $@
        ;;
    *)
        echo "Not a valid comonent name $CB_TASK_COMPONENT"
        exit 1
        ;;
esac
