#!/bin/bash

# @file create-homestead-prov-nginx-config
#
# Copyright (C) Metaswitch Networks 2015
# If license terms are provided to you in a COPYING file in the root directory
# of the source code repository by which you are accessing this code, then
# the license outlined in that COPYING file applies to your use.
# Otherwise no rights are granted except for those provided to you by
# Metaswitch Networks in a separate written agreement.

# This file creates an nginx config file for homestead-prov.

split_domain_and_port()
{
  echo $1 | perl -ne '$_ =~ /(.+):([0-9]+)$/ && print "$1 $2\n"'
}

. /etc/clearwater/config

# Only create the nginx config if the hs_provisioning_hostname has been set.
# We need this configuration when Homestead-prov is running on a multiple
# networks system; if this isn't created then poll_homestead_prov will fail
# and cyclically reboot Homestead-prov (on a multiple networks system)
if [ -n "$hs_provisioning_hostname" ]
then
  read -r hs_provisioning_domain hs_provisioning_port <<< "$(split_domain_and_port $hs_provisioning_hostname)"

  [ ! -z $homestead_provisioning_port ] || homestead_provisioning_port=$hs_provisioning_port

  site_file=/etc/nginx/sites-available/homestead-prov
  enabled_file=/etc/nginx/sites-enabled/homestead-prov
  temp_file=$(mktemp homestead-prov.nginx.XXXXXXXX)
  let sock_seq_end=$(cat /proc/cpuinfo | grep processor | wc -l)-1

  cat > $temp_file << EOF1
  upstream http_homestead_prov {
EOF1

  for sock_index in `seq 0 $sock_seq_end`;
  do
    echo "        server unix:/tmp/.homestead-prov-sock-$sock_index;" >> $temp_file
  done

  cat >> $temp_file << EOF2

        # The minimum number of idle connections to keep alive to the upstream.
        keepalive 16;
}

server {
        listen       [::]:$homestead_provisioning_port ipv6only=off;
        server_name  $hs_provisioning_domain;

        location / {
                proxy_pass http://http_homestead_prov;
                proxy_http_version 1.1;

                # The client may have instructed the server to close the
                # connection - do not forward this upstream.
                proxy_set_header Connection "";
        }
}
EOF2

  if ! diff $temp_file $enabled_file > /dev/null 2>&1
  then
    # Update the site file
    mv $temp_file $site_file

    # Enable the homestead-prov nginx site
    if ( nginx_ensite homestead-prov > /dev/null )
    then
      service nginx stop
    fi
  else
    rm $temp_file
  fi
fi
