#!/bin/sh

. /lib/functions.sh

update_default_nginx_listner() {
  if [ ! -f "/etc/config/nginx" ]; then
    return 0
  fi

  if ! uci_get nginx _lan >/dev/null 2>&1; then
    return 0
  fi

  if ! opkg list-installed | grep -q "^luci "; then
    echo "Luci not installed, removing luci config"
    uci_remove nginx _lan
    uci_remove nginx _redirect2ssl
  else
    uci_remove nginx _lan listen
    uci_add_list nginx _lan listen "8443 ssl default_server"
    uci_add_list nginx _lan listen "[::]:8443 ssl default_server"

    if ! uci_get nginx _redirect2ssl >/dev/null 2>&1; then
        return 0
    fi

    uci_remove nginx _redirect2ssl listen
    uci_add_list nginx _redirect2ssl listen "8080"
    uci_add_list nginx _redirect2ssl listen "[::]:8080"
    uci_set nginx _redirect2ssl return '302 https://$host:8443$request_uri'
  fi
}

move_sulu_to_443_and_80() {
  if ! config_load userinterface; then
    return 0
  fi

  set_port() {
    local protocol port

    config_get protocol "$1" protocol
    config_get port "$1" port

    if [ "$protocol" == "HTTPS" ] && [ "${port}" -eq "8443" ]; then
      uci_set userinterface "$1" port "443"
    elif [ "$protocol" == "HTTP" ] && [ "${port}" -eq "8080" ]; then
      uci_set userinterface "$1" port "80"
    fi
  }
  config_foreach set_port http_access
}

update_default_nginx_listner
move_sulu_to_443_and_80
