brooklyn.parameters:
  - name: target_ips
    description: List of IP addresses
    pinned: true
    type: list<string>
    constraints:
      - required

  - name: target_port
    description: Port at target IPs which should be targetted
    pinned: true
    type: integer
    defaultValue: 80

services:
- type: workflow-software-process
  name: Nginx Load Balancer
  brooklyn.config:
    http.port: 80
    install.workflow:
      steps:
        - ssh sudo apt install nginx jq -y
        - ssh sudo systemctl enable nginx
    customize.workflow:
      steps:
        - invoke-effector regenerate-config
    launch.workflow:
      steps:
        - ssh sudo systemctl start nginx
        - step: set-sensor
          sensor:
            name: main.uri
            entity: $brooklyn:parent()
          value: http://${entity.sensor['host.address']}/

    checkRunning.workflow:
      steps:
        - 'ssh sudo systemctl status nginx | grep "Active: active"'

    stop.workflow:
      steps:
        - ssh sudo systemctl stop nginx

  brooklyn.initializers:
    - type: workflow-effector
      name: regenerate-config
      steps:
        - wait ips = ${entity.config.target_ips}
        - step: |
            ssh <<EOF_SSH sudo bash
            cat >/tmp/load-balancer.conf <<EOF_CAT
            upstream backend {
            $(echo $IPS | jq -rc '.[]' | while read x ; do echo "  server $x:${entity.config.target_port};" ; done)
            }
            
            server {
              listen ${entity.config['http.port']} default_server;
            
              location / {
                proxy_pass http://backend;
              }
            }
            EOF_CAT
            mv /tmp/load-balancer.conf /etc/nginx/conf.d/
            if [ -f /etc/nginx/sites-enabled/default ]; then
              mkdir -p /etc/nginx/sites-disabled
              mv /etc/nginx/sites-enabled/default /etc/nginx/sites-disabled
            fi
            EOF_SSH
          env:
            IPS: ${ips}
        - ssh sudo systemctl restart nginx
