#!/bin/bash

# @file create-homestead-nginx-config
#
# Copyright (C) Metaswitch Networks 2016
# 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.

. /etc/clearwater/config

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

if [ -n "$hs_hostname_mgmt" ]
then
  site_file=/etc/nginx/sites-available/homestead
  enabled_file=/etc/nginx/sites-enabled/homestead
  temp_file=$(mktemp homestead.nginx.XXXXXXXX)
  server_name_and_port=( $( split_domain_and_port $hs_hostname_mgmt ) )

  cat > $temp_file << EOF
upstream http_homestead {
        server unix:/tmp/homestead-http-mgmt-socket;

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

server {
        listen       [::]:8886 ipv6only=off;
        server_name  ${server_name_and_port[0]};

        location / {
                proxy_pass http://http_homestead;
                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 "";
        }
}
EOF

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

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