#!/bin/bash

echo "Quick StarCluster cluster builder by Przemyslaw.Szufel@bidelastic.com"
echo "This code is licensed under the terms of AGPL open source license"

if [ ! -f credentials.csv ];then

    echo "Credentials.csv file not found"
    echo "In order to obtaint credentials.csv please follow the steps"
    echo "1. Go to https://console.aws.amazon.com/ "
	echo "2. Select >IAM< in the >services< menu and go to >users<"
	echo "3. Select an existing user or create a new one"
	echo "4. Click >Manage Access Keys< and >Create Access Key<"
	echo "5. Click >Download credentials< and save credentials.csv"
	exit
fi


while IFS="," read f1 f2 f3 
do 
   echo "Reading credentials.csv $f1 $f2 $f3" 
done < credentials.csv

sudo apt-get update
sudo apt-get -y install build-essential libssl-dev libffi-dev python-dev python-setuptools mc


#easy_install --upgrade pip

sudo easy_install StarCluster

DEVELOP version
wget https://github.com/jtriley/StarCluster/archive/develop.zip
unzip develop.zip
cd StarCluster-develop
patch to support SimulationNode role
curl https://szufel.pl/awsutils.py > starcluster/awsutils.py
sudo python setup.py install
cd ~




mkdir ~/.starcluster

python -c 'from starcluster.templates import config;from os.path import expanduser;f=open(expanduser("~")+"/.starcluster/config","w");f.write(config.config_template);f.close()'

chmod 600 ~/.starcluster/config

uncomment() {
    sed -i "s/^# $1/$1/g" ~/.starcluster/config
}
setconfig() {
    sed -i "s/^#$1 /$1/g" ~/.starcluster/config
    sed -i "s#^\($1\s*=\s*\).*\$#\1$2#" ~/.starcluster/config	
}

setconfig AWS_REGION_NAME "us-east-1"
setconfig AVAILABILITY_ZONE "us-east-1e"
setconfig AWS_REGION_HOST "ec2.us-east-1.amazonaws.com"
setconfig CLUSTER_SIZE "5"
setconfig NODE_IMAGE_ID "ami-d66ed4c1"
setconfig NODE_INSTANCE_TYPE "c3.large"
setconfig MASTER_INSTANCE_TYPE "c3.large"
setconfig AWS_ACCESS_KEY_ID $f2
setconfig AWS_SECRET_ACCESS_KEY $f3
setconfig AWS_USER_ID ${f1//\"/}



#disable execution on master
setconfig PLUGINS sge
uncomment "\\[plugin sge\\]"
uncomment "SETUP_CLASS = starcluster.plugins.sge.SGEPlugin"
uncomment "MASTER_IS_EXEC_HOST = False"
uncomment "DISABLE_QUEUE=True"
starcluster createkey mykey -o ~/.ssh/mykey.rsa

echo Cluster setup completed. Now you can run \(with \$0.20 spot bid\):
echo starcluster start -b 0.20 cluster_name 
