#!/bin/bash

# @file create-homer-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 homer.

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

. /etc/clearwater/config

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

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

  cat > $temp_file << EOF1
upstream http_homer {
EOF1

  for sock_index in `seq 0 $sock_seq_end`;
  do
    echo "        server unix:/tmp/.homer-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       [::]:$xdms_port ipv6only=off;
        server_name  $xdms_domain;

        location / {
                proxy_pass http://http_homer;
                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 homer > /dev/null )
    then
      service nginx stop
    fi
  else
    rm $temp_file
  fi
fi
