#!/bin/bash

set -euEo pipefail

this_host=$(ngcp-hostname)
# shellcheck disable=SC2046
read -ra web_int <<< $(ngcpcfg get "argv.host = '${this_host}'; argv.type = 'web_int'; PROCESS '/usr/lib/ngcp-ngcpcfg/get_all_ips_for_host'; out")

for ip in "${web_int[@]}"; do
  if ! [[ "${ip}" == '127.0.0.1' ]]; then
    echo "Using '${ip}' as interface for ngcp-management-ui"
    sed -ri "s/<mgmt_api_ip>/${ip}/" \
      /etc/nginx/sites-available/ngcp-management-ui
  fi
done

echo "Enabling ngcp-management-ui web interface"
ln -s /etc/nginx/sites-available/ngcp-management-ui \
  /etc/nginx/sites-enabled/ngcp-management-ui

echo "Testing nginx configuration"
nginx -t

echo "Reload nginx"
systemctl reload nginx

echo "Commiting changes in /etc"
pushd /etc &>/dev/null
etckeeper commit "Enable ngcp-management-ui"
popd &>/dev/null
