#!/bin/bash

set -e

node_type=${1}

# Start munge
service munge start

/wait_for_it.sh elasticsearch:9200

echo "waiting for mysql"
until mysqladmin -u root -ptoxic8_teary ping -h mysql --silent; do
    sleep 1
done
echo "mysql is up"

if [ ${node_type} == "master" ]; then
    echo "Configuring ElasticSearch"
    # Set up ES schema
    curl -XPUT elasticsearch:9200/pipedream -d '{
      "mappings": {
        "pipe_info": {
          "properties": {
            "name" : {
              "type" : "string",
              "fields" : {
                "raw" : {
                  "type" : "string",
                  "index" : "not_analyzed"
                }
              }
            },
            "pipe_id" : {
              "type" : "string",
              "fields" : {
                "keyword" : {
                  "type" : "string",
                  "index" : "not_analyzed"
                }
              }
            },
            "start_timestamp": { "type": "date" },
            "end_timestamp": { "type": "date" }
          }
        },
        "configs": {
          "properties": {
            "name" : {
              "type" : "string",
              "fields" : {
                "raw" : {
                  "type" : "string",
                  "index" : "not_analyzed"
                }
              }
            }
          }
        }
      }
    }'
    curl -X PUT elasticsearch:9200/metrics -d '{
      "mappings": {
        "metric": {
          "properties": {
            "name" : {
              "type" : "string",
              "fields" : {
                "raw" : {
                  "type" : "string",
                  "index" : "not_analyzed"
                }
              }
            },
            "pipe_id" : {
              "type" : "string",
              "fields" : {
                "keyword" : {
                  "type" : "string",
                  "index" : "not_analyzed"
                }
              }
            }
          }
        }
      }
    }'
    echo "Configured elasticsearch"

    echo "Setting up MySQL"
    mysql -u root -ptoxic8_teary -h mysql -e "CREATE USER 'slurm'@'%' IDENTIFIED BY 'toxic8_teary';"
    mysql -u root -ptoxic8_teary -h mysql -e "GRANT ALL PRIVILEGES ON * . * TO 'slurm'@'%';"
    mysql -u root -ptoxic8_teary -h mysql -e "FLUSH PRIVILEGES;"
    echo "MYSQL setup"

    # Set up slurm accounts
    service slurmdbd start
    sleep 2
    yes | sacctmgr add cluster slurm_cluster
    yes | sacctmgr add account slurm Cluster=slurm_cluster
    yes | sacctmgr add user slurm DefaultAccount=slurm
    yes | sacctmgr add user one_more DefaultAccount=slurm

    # Set up slurm QoS
    yes | sacctmgr add qos preemptible
    yes | sacctmgr add qos critical Preempt=preemptible
fi

mknod /dev/tty0 c 4 0
# Start slurm, update its conf information, and start SSH
echo "Starting SLURM"
/get_slurm_info.py
echo "Really starting SLURM"
service slurm start
echo "Starting sshd"
/usr/sbin/sshd -D -e
