#!/bin/bash

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

. /etc/clearwater/config

if [ -n "$home_domain" ] && [ -n "$public_hostname" ] && [ -n "$local_ip" ] && [ -n "$public_ip" ]
then
  ellis_hostname=${ellis_hostname:-ellis.$home_domain}
  site_file=/etc/nginx/sites-available/ellis
  enabled_file=/etc/nginx/sites-enabled/ellis
  ssl_cert_file=/etc/nginx/ssl/ellis.crt
  ssl_key_file=/etc/nginx/ssl/ellis.key
  temp_file=$(mktemp ellis.nginx.XXXXXXXX)

  # Read common config into variables, to avoid duplication in this script.

  read -r -d '' common_server_config << EOM
        listen       [::]:80 default_server ipv6only=off;
        server_name  $ellis_hostname $local_ip $public_ip $public_hostname;
EOM

  read -r -d '' location_config << EOM2
        location / {
                proxy_pass http://http_ellis;
                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 "";

                # Preserve the Ellis hostname.
                proxy_set_header Host $ellis_hostname;
        }
EOM2

  # Write the ellis config to file, in multiple sections.

  cat > $temp_file << EOF1
upstream http_ellis {
EOF1

    echo "        server unix:/tmp/.ellis-sock;" >> $temp_file

  cat >> $temp_file << EOF2
        # The minimum number of idle connections to keep alive to the upstream.
        keepalive 16;
}
EOF2

  if [ -e "$ssl_cert_file" ] && [ -e "$ssl_key_file" ]
  then
    cat >> $temp_file << EOF3
server {
        ssl on;
        ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
        ssl_session_timeout 5m;
        ssl_ciphers "HIGH:!aNULL:!MD5 or HIGH:!aNULL:!MD5:!3DES";
        ssl_prefer_server_ciphers on;

        ssl_certificate $ssl_cert_file;
        ssl_certificate_key $ssl_key_file;

        listen       [::]:443 ipv6only=off;
        server_name  $ellis_hostname $local_ip $public_ip $public_hostname;

        $location_config
}

server {
        $common_server_config

        return       301   https://\$host\$request_uri;
}
EOF3

  else

    cat >> $temp_file << EOF4
server {
        $common_server_config

        $location_config
}
EOF4

  fi

  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 ellis > /dev/null )
    then
      service nginx stop
    fi
  else
    rm $temp_file
  fi
fi
