#!/bin/bash

  # Retrieve script arguments
  NUM_WORKERS=$1                  # Number of container workers
  APP_IMAGE_NAME=$2               # Application image name. With username: 'john123/my-app'
  ABS_CONTEXT=$3                  # Absolute path where the context dir is located. This must be specified by the app-image provider.
  COMPUTING_UNITS=$4
  MEMORY=$5
  SWARM_MANAGER_IP=$6
  CREATION_TIME=$7
  MIN_VMS=$8
  MAX_VMS=$9
  shift 9
  RUNCOMPSS_ARGS=$*     # From here on, the typical runcompss parameters you would use

  #
  # This will include: creating the xml's inside master container, executing runcompss, and shutting down workers.
  #
  master_command="/bin/bash -c '"
  CLOUD="False"
  if [ ${MAX_VMS}  -gt 0 ]; then
    CLOUD="True"
  fi
  # Create project and resources
  master_command="${master_command} /opt/COMPSs/Runtime/scripts/system/docker/generate_docker_resources.sh $ABS_CONTEXT/resources.xml $NUM_WORKERS $COMPUTING_UNITS $MEMORY $SWARM_MANAGER_IP $APP_IMAGE_NAME $CLOUD $CREATION_TIME ; "
  master_command="${master_command} /opt/COMPSs/Runtime/scripts/system/docker/generate_docker_project.sh $ABS_CONTEXT/project.xml $NUM_WORKERS $APP_IMAGE_NAME $MIN_VMS $MAX_VMS ; "
  
  # Add their path to the runcompss args
  RUNCOMPSS_ARGS=" --resources=\"$ABS_CONTEXT/resources.xml\" $RUNCOMPSS_ARGS"
  RUNCOMPSS_ARGS=" --project=\"$ABS_CONTEXT/project.xml\"  $RUNCOMPSS_ARGS"
  RUNCOMPSS_ARGS=" --master_name=master $RUNCOMPSS_ARGS"
  # Execute the runcompss command itself, from the context directory
  master_command="${master_command} cd \"${ABS_CONTEXT}\"; sleep 5 ; /opt/COMPSs/Runtime/scripts/user/runcompss $RUNCOMPSS_ARGS 2>&1; "
  
  # After the execution ends, stop all the workers. This is, stop their sshd
  # Concatenating with ; to ALWAYS shutdown nodes even if the above commands fail
  for i in $(seq 1 "$NUM_WORKERS"); do
      master_command="${master_command} ssh -o StrictHostKeyChecking=no worker${i} \"pkill sshd\" ;"
  done
  
  master_command="${master_command} exit 0 '" # Final quotes huehue

  #
  # Now, we are going to create the Docker Compose file.
  # One service for the master, and one service for each worker
  #

  # GENERAL
  echo -e "\
version: '3.0'

networks:
  runcompss-docker-net:
    driver: overlay

services:
"

  # WORKERS
  for i in $(seq 1 "${NUM_WORKERS}"); do
    echo -e "\
  worker$i:
    image: $APP_IMAGE_NAME

    command: /bin/bash -c \"/usr/sbin/sshd -D \"
    deploy:
      restart_policy:
        condition: none
        delay: 5s
        window: 10s
      resources:
        limits:
          memory: ${MEMORY}g
          cpus: '${COMPUTING_UNITS}'

    networks:
      - runcompss-docker-net
"
  done

  # MASTER
  echo -e "\
  master:

    image: $APP_IMAGE_NAME

    command: ${master_command}

    deploy:
      restart_policy:
        condition: none
        delay: 5s
        window: 10s

    networks:
      - runcompss-docker-net
"
