#!/bin/sh

#V7

REGISTRY_BASE=registry.cair.ru

CLICKHOUSE_USER=logging
FQDN=n2gfw.com
SS_CERT=0

ADMIN_PASSWORD=$(tr -dc A-Za-z0-9 </dev/urandom | head -c 13 ; echo '')
CLICKHOUSE_PASSWORD=$(tr -dc A-Za-z0-9 </dev/urandom | head -c 13 ; echo '')
API_KEY=$(tr -dc A-Za-z0-9 </dev/urandom | head -c 36 ; echo '')

CURRENT_HOST=`hostname -f`

# install software
if [ "$(which docker)" = "" ]; then
  sudo apt install -y docker
fi

if [ ! -f /usr/local/bin/docker-compose ]; then
  sudo apt install -y gnupg2 pass
  gpg2 --full-generate-key
  curl -SL https://github.com/docker/compose/releases/download/v2.17.2/docker-compose-linux-x86_64 -o /usr/local/bin/docker-compose
  chmod +x /usr/local/bin/docker-compose
fi

if ! [ -x "$(command -v openssl)" ]; then
  echo 'Error: openssl is not installed.' >&2
  exit 1
fi

mkdir -p /etc/nngf/

create_config_env() {
 mkdir -p /etc/nngf
 cat > /etc/nngf/config.env <<_EOF_
NETFLOW_DST=192.168.0.1:2055
NETFLOW_PROTO=10
INTERNAL_IF=isolated
EXTERNAL_IF=outside
CONTROL_IF=control
INTERFACE=\${EXTERNAL_IF}:\${INTERNAL_IF}
BRIDGE_IF=br0
HOME_NET=192.168.0.100/32
EXTERNAL_NET=!192.168.0.100/32
INLINE=l2
POLICY=block
_EOF_
}

create_ch_init() {

mkdir -p /etc/nngf/clickhouse/

cat >/etc/nngf/clickhouse/init-defaults.sh <<_EOF_
#!/bin/bash

CLICKHOUSE_USER="\${CLICKHOUSE_USER:-user}";
CLICKHOUSE_PASSWORD="\${CLICKHOUSE_PASSWORD:-password}";

echo "<yandex>
  <!-- Docs: <https://clickhouse.tech/docs/en/operations/settings/settings_users/> -->
  <users>
    <\${CLICKHOUSE_USER}>
      <profile>default</profile>
      <networks>
        <ip>::/0</ip>
      </networks>
      <password>\${CLICKHOUSE_PASSWORD}</password>
      <quota>default</quota>
    </\${CLICKHOUSE_USER}>
  </users>
</yandex>" >/etc/clickhouse-server/users.d/user.xml

cat /etc/clickhouse-server/users.d/user.xml;

clickhouse-client --user \${CLICKHOUSE_USER} --password \${CLICKHOUSE_PASSWORD} --query "CREATE DATABASE IF NOT EXISTS logs";
echo -n "
CREATE TABLE IF NOT EXISTS logs.records
(
    timestamp DateTime64(9),
    Message String,
    Priority UInt8,
    AppID String,
    Proto String,
    SrcIP String,
    SrcPort UInt16,
    DstIP String,
    DstPort UInt16,
    Classification String,
    host LowCardinality(String),
    source LowCardinality(String),
    uuid UUID DEFAULT '00000000-0000-0000-0000-000000000000'

)
ENGINE = MergeTree
PARTITION BY toStartOfHour(timestamp)
ORDER BY (host, timestamp)
SETTINGS index_granularity = 8192;" | clickhouse-client --user \${CLICKHOUSE_USER} --password \${CLICKHOUSE_PASSWORD}
_EOF_

}

create_server_fb() {
 mkdir -p /etc/nngf/fluent-bit
 cat >/etc/nngf/fluent-bit/server-fluent-bit.conf <<_EOF_
[SERVICE]
    Flush         1
    Log_Level     warning
    Daemon        off
    Parsers_File  parsers.conf
    HTTP_Server   On
    HTTP_Listen   0.0.0.0
    HTTP_Port     2020
#    storage.sync              normal
#    storage.checksum          off
#    storage.backlog.mem_limit 5M

[INPUT]
    Buffer_Chunk_Size   32000
    Buffer_Max_Size     64000
    Name     forward
    Listen   0.0.0.0
    Port     1514
    storage.type  memory
    mem_buf_limit       1G
    Tag  snortlog

[FILTER]
    Name parser
    Match *
    Parser   fast-alert
    Key_Name log
    Reserve_Data On
    Preserve_Key On

[FILTER]
    Name grep
    Match *
    Logical_Op or
    Regex Message ^.+$
    Regex AppID ^.+$
    Regex Proto ^.+$
    Regex Classification ^.+$
    Regex Priority ^.+$

[FILTER]
    Name modify
    Match *
    Remove log
    Remove container_id
    Remove container_name
    Remove DateTime
    Add Message ""
    Add AppID ""
    Add Proto ""
    Add SrcIP ""
    Add SrcPort ""
    Add DstIP ""
    Add DstPort ""
    Add Classification ""
    Add Priority ""
    Add source "stdout"

[FILTER]
    Name lua
    Match *
    script override_time.lua
    call append_tag

[OUTPUT]
    Name  stdout
    Match *

[OUTPUT]
    Match *
    Name http
    Host clickhouse.localhost
    Port 8123
    http_User logging
    http_Passwd DxFer495bCsD
    URI /?query=INSERT+INTO+logs.records+FORMAT+JSONEachRow
    Format json_stream
    Json_date_key  timestamp
    Json_date_format epoch
    Retry_Limit     5
    storage.total_limit_size  1G

_EOF_
 cat >/etc/nngf/fluent-bit/server-parsers.conf <<_EOF_
[PARSER]
    Name        syslog
    Format      regex
    Regex       ^\<(?<pri>[0-9]+)\>(?<time>[^ ]* {1,2}[^ ]* [^ ]*) (?<host>[^ ]*) (?<ident>[a-zA-Z0-9_\/\.\-]*)(?:\[(?<pid>[0-9]+)\])?(?:[^\:]*\:)? *(?<message>.*)$
    Time_Key    time
    Time_Format %b %d %H:%M:%S
    Types pid:integer
    Types pri:integer

[PARSER]
    Name        syslog-rfc5424
    Format      regex
    Regex       ^\<(?<pri>[0-9]{1,5})\>1 (?<time>[^ ]+) (?<host>[^ ]+) (?<ident>[^ ]+) (?<pid>[-0-9]+) (?<msgid>[^ ]+) (?<extradata>(\[(.*)\]|-)) (?<message>.+)$
    Time_Key    time
    Time_Format %Y-%m-%dT%H:%M:%S.%L
    Time_Keep   On
    Types pid:integer

[PARSER]
    Name        fast-alert
    Format      regex
    Regex       ^(?<DateTime>[0-9:.\/-]+)\ .*\ (\[\d+:\d+:\d+])\ ("(?<Message>[^\[]*)")*\ (\[\*\*]\ )?(\[Classification:\ (?<Classification>[^\]]+]*)\]\ )?(\[Priority:\ (?<Priority>\d)]\ )?(\[AppID:\ (?<AppID>[^\]]+)\]\ )?{(?<Proto>.*)}\ (?<SrcIP>\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}):(?<SrcPort>\d{1,5})\s+->\s+(?<DstIP>\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}):(?<DstPort>\d{1,5})$
    Time_Format %m/%d-%H:%M:%S.%L
    Time_Keep   On
    Time_Key    DateTime

_EOF_

cat >/etc/nngf/fluent-bit/override_time.lua <<_EOF_
function append_tag(tag, timestamp, record)
    new_record = record
    new_record["timestamp"] = os.date("%Y-%m-%d %H:%M:%S")
    return 1, timestamp, new_record
end
_EOF_
}


create_collector_fb() {
 mkdir -p /etc/nngf/fluent-bit
 cat >/etc/nngf/fluent-bit/collector-fluent-bit.conf <<_EOF_
[SERVICE]
    Flush      5
    Daemon     off
    Log_Level  info

#[INPUT]
#    Name        tail
#    Path        /log/linelog
[INPUT]
    Name forward
    Listen 0.0.0.0
    port 24224


[FILTER]
    Name modify
    Match *
    Add host "${CURRENT_HOST}"
    Add uuid "`cat /etc/machine-id || echo '00000000-0000-0000-0000-00000000000'`"

#[OUTPUT]
#    Name   stdout
#    Match  *

[OUTPUT]
    Name          forward
    Match         *
    Host          $FQDN
    Port          1514

_EOF_
}




create_ss_cert() {

# Create root CA & Private key
cd /tmp || exit
openssl req -x509 -sha256 -days 356 -nodes -newkey rsa:2048 -subj "/CN=${FQDN}/C=US/L=San Fransisco" -keyout /tmp/rootCA.key -out /tmp/rootCA.crt
openssl genrsa -out /tmp/server.key 2048

cat > /tmp/csr.conf <<EOF
[ req ]
default_bits = 2048
prompt = no
default_md = sha256
req_extensions = req_ext
distinguished_name = dn

[ dn ]
C = US
ST = California
L = San Fransisco
O = NNGF
OU = NNGF TLS
CN = ${FQDN}

[ req_ext ]
subjectAltName = @alt_names

[ alt_names ]
DNS.1 = ${FQDN}
DNS.2 = www.${FQDN}
IP.1 = 192.168.1.5
IP.2 = 192.168.1.6

EOF

openssl req -new -key /tmp/server.key -out /tmp/server.csr -config /tmp/csr.conf
# csr.conf, server.csr and server.key

cat > /tmp/cert.conf <<EOF

authorityKeyIdentifier=keyid,issuer
basicConstraints=CA:FALSE
keyUsage = digitalSignature, nonRepudiation, keyEncipherment, dataEncipherment
subjectAltName = @alt_names

[alt_names]
DNS.1 = ${FQDN}

EOF

openssl x509 -req -in /tmp/server.csr -CA /tmp/rootCA.crt -CAkey /tmp/rootCA.key -CAcreateserial -out /tmp/server.crt -days 365 -sha256 -extfile /tmp/cert.conf

# server.crt that will be used with our server.key

mkdir -p /etc/nngf/certbot/conf/live/$FQDN/
cat  /tmp/server.crt > /etc/nngf/certbot/conf/live/$FQDN/fullchain.pem
cp   /tmp/server.key /etc/nngf/certbot/conf/live/$FQDN/privkey.pem

}

request_cert() {
# check cert already installed
if [ ! -d /etc/nngf/certbot/conf/live ] || [ ! $(ls /etc/nngf/certbot/conf/live | wc -l) -gt 1 ]; then
  mkdir -p /etc/nngf/nginx/conf

  cat > /etc/nngf/nginx/conf/nginx.conf << _EOF_
server {
    listen 80;
    server_name _;
    server_tokens off;
    client_max_body_size 20M;

    location / {
    }

    location /.well-known/acme-challenge/ {
        root /var/www/certbot;
    }

}
_EOF_

  cat > /etc/nngf/certbot-startup.docker-compose.yml << _EOF_
version: "3"

services:
  webserver:
    restart: unless-stopped
    image: nginx:1.19.6
    ports:
      - 80:80
      - 443:443
    volumes:
      - /etc/nngf/nginx/conf/:/etc/nginx/conf.d/:ro
      - /etc/nngf/certbot/www:/var/www/certbot/:ro
      - /etc/nngf/certbot/conf/:/etc/nginx/ssl/:ro

  certbot:
#    restart: unless-stopped
    image: certbot/certbot:latest
    volumes:
      - /etc/nngf/certbot/www/:/var/www/certbot/:rw
      - /etc/nngf/certbot/conf/:/etc/letsencrypt/:rw
    command: "certonly --webroot -w /var/www/certbot/ -d ${FQDN} --non-interactive --agree-tos --register-unsafely-without-email"

_EOF_

  /usr/local/bin/docker-compose -f /etc/nngf/certbot-startup.docker-compose.yml up -d
  while [ ! $(docker ps -a | grep 'nngf-certbot-1' | grep  'Exited' > /dev/null 2>&1 ; echo $? ) -eq '0' ]; do echo 'waiting for container to become ready...'; sleep 1; done;
  /usr/local/bin/docker-compose -f /etc/nngf/certbot-startup.docker-compose.yml down

  if [ ! -f /etc/nginx/ssl/live/$FQDN/fullchain.pem ]; then
    echo "Fail to request acme cert, create self-signed."
    create_ss_cert
    SS_CERT=1
  fi

else
  echo "Certificate already requested"
fi
rm -f /etc/nngf/certbot-startup.docker-compose.yml

}

install_controller(){
 create_ch_init
 create_server_fb

 cat > /etc/nngf/docker-compose.yml << _EOF_
version: "3"

services:
  frontend:
    image: ${REGISTRY_BASE}/nngf/nngf-front:latest
    restart: unless-stopped

  backend:
    image: ${REGISTRY_BASE}/nngf/backend:latest
    restart: unless-stopped
    environment:
      ADMIN_PASSWORD: ${ADMIN_PASSWORD}
    volumes:
      - backend-db:/var/www/db/

  certbot:
    restart: unless-stopped
    image: certbot/certbot:latest
    volumes:
      - /etc/nngf/certbot/www/:/var/www/certbot/:rw
      - /etc/nngf/certbot/conf/:/etc/letsencrypt/:rw
    entrypoint: "/bin/sh -c 'trap exit TERM; while :; do certbot renew; sleep 12h & wait \$\${!}; done;'"


  webserver:
    restart: unless-stopped
    image: nginx:1.19.6
    ports:
      - 80:80
      - 443:443
    volumes:
      - /etc/nngf/nginx/conf/:/etc/nginx/conf.d/:ro
      - /etc/nngf/certbot/www:/var/www/certbot/:ro
      - /etc/nngf/certbot/conf/:/etc/nginx/ssl/:ro
    depends_on:
      - frontend
      - backend
      - daemon

  database:
    image: yandex/clickhouse-server
    restart: unless-stopped
    #network_mode: host
    ports:
      - "8123:8123"
      - "9000:9000"
      - "9009:9009"
    volumes:
      - clickhouse-data:/var/lib/clickhouse
      - /etc/nngf/clickhouse/init-defaults.sh:/docker-entrypoint-initdb.d/init-defaults.sh:ro
    environment:
      # Default user and database will be created using init-defaults.sh script
      CLICKHOUSE_USER: ${CLICKHOUSE_USER}
      CLICKHOUSE_PASSWORD: ${CLICKHOUSE_PASSWORD}
    hostname: clickhouse.localhost
    ulimits:
      nproc: 65535
      nofile:
       soft: 262144
       hard: 262144

  fluent-bit-server:
    network_mode: host
    image: fluent/fluent-bit
    restart: unless-stopped
    volumes:
      - /etc/nngf/fluent-bit/server-fluent-bit.conf:/fluent-bit/etc/fluent-bit.conf
      - /etc/nngf/fluent-bit/server-parsers.conf:/fluent-bit/etc/parsers.conf
      - /etc/nngf/fluent-bit/override_time.lua:/fluent-bit/etc/override_time.lua
    ports:
      - "1514:1514"


volumes:
  backend-db:
  clickhouse-data:
_EOF_

  /usr/local/bin/docker-compose -f /etc/nngf/docker-compose.yml pull

  ## Add nginx
  cat > /etc/nngf/nginx/conf/nginx.conf << _EOF_
server {
    listen 80;
    server_name _;
    server_tokens off;
    client_max_body_size 20M;

    location /.well-known/acme-challenge/ {
        root /var/www/certbot;
    }

    location / {
        return 301 https://\$host\$request_uri;
    }

}

server {
    listen 443 default_server ssl http2;
    listen [::]:443 ssl http2;
    server_name _;

    ssl_certificate /etc/nginx/ssl/live/$FQDN/fullchain.pem;
    ssl_certificate_key /etc/nginx/ssl/live/$FQDN/privkey.pem;

    location / {
      try_files $uri $uri/ @frontend;
    }

        location @frontend {
        proxy_set_header X-Forwarded-Proto https;
        proxy_set_header X-Url-Scheme \$scheme;
        proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;
        proxy_set_header Host \$http_host;
        proxy_redirect off;
        proxy_pass   http://frontend:80;
        }

    location /api {
        proxy_set_header X-Forwarded-Proto https;
        proxy_set_header X-Url-Scheme \$scheme;
        proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;
        proxy_set_header Host \$http_host;
        proxy_redirect off;
        proxy_pass   http://backend:80;
    }
}
_EOF_

  /usr/local/bin/docker-compose -f /etc/nngf/docker-compose.yml up -d
}

install_service() {
 create_config_env
 create_collector_fb
 mkdir -p /etc/nngf/shared
 cat > /etc/nngf/docker-compose.yml << _EOF_
version: "3"

services:
  firewall:
    image: ${REGISTRY_BASE}/nngf/ipt-netflow:master
    privileged: true
    network_mode: host
    command:
      - "iptables"
      - "-vnL"
    env_file:
      - config.env
    container_name: firewall
    volumes:
      - /usr/src:/usr/src
      - /lib/modules:/lib/modules
      - /usr/lib/modules:/usr/lib/modules
      - /etc/nngf/shared/:/shared

  snort:
    image: ${REGISTRY_BASE}/nngf/snort3:master
    user: root
    privileged: true
    cap_add:
      - NET_ADMIN
    container_name: snort3
    env_file:
      - config.env
    volumes:
      - /usr/src:/usr/src
      - /lib/modules:/lib/modules
      - /usr/lib/modules:/usr/lib/modules
      - /etc/nngf/shared/:/shared
    pid: "service:firewall"
    network_mode: "host"
    depends_on:
      - fluent-bit-collector
      - firewall
    logging:
      driver: fluentd
      options:
        fluentd-async: "true"

  daemon:
    image: ${REGISTRY_BASE}/nngf/daemon:latest
    container_name: daemon
    restart: unless-stopped
    environment:
      API_KEY: ${API_KEY}
      CERT_PATH: /etc/nginx/ssl/live/$FQDN/fullchain.pem
      KEY_PATH : /etc/nginx/ssl/live/$FQDN/privkey.pem
      LISTEN_PORT: 443
      ENDPOINT_PREFIX: '/daemon'
      USE_TLS: yes
      SHARED_DAEMON_FOLDER: /shared
      SHARED_FW_FOLDER: /shared
    ports:
      - 443:443
    volumes:
      - /etc/nngf/certbot/conf/:/etc/nginx/ssl/:ro
      - /etc/nngf/shared/:/shared
      - /var/run/docker.sock:/var/run/docker.sock:rw
      - /etc/nngf/:/etc/nngf:rw
      - /etc/machine-id:/etc/machine-id:ro
      - /var/lib/dbus/machine-id:/var/lib/dbus/machine-id:ro

  fluent-bit-collector:
    image: fluent/fluent-bit
    restart: unless-stopped
    ports:
      - "24224:24224"
      - "24224:24224/udp"
    volumes:
      - /etc/nngf/fluent-bit/collector-fluent-bit.conf:/fluent-bit/etc/fluent-bit.conf

_EOF_
 /usr/local/bin/docker-compose -f /etc/nngf/docker-compose.yml up -d
}

install_all() {
 create_config_env
 create_server_fb
 create_collector_fb
 create_ch_init
 cat > /etc/nngf/docker-compose.yml <<_EOF_
version: "3"

services:
  firewall:
    image: ${REGISTRY_BASE}/nngf/ipt-netflow:master
    privileged: true
    network_mode: host
    command:
      - "iptables"
      - "-vnL"
    env_file:
      - config.env
    container_name: firewall
    volumes:
      - /usr/src:/usr/src
      - /lib/modules:/lib/modules
      - /usr/lib/modules:/usr/lib/modules
      - /etc/nngf/shared/:/shared

  snort:
    image: ${REGISTRY_BASE}/nngf/snort3:master
    user: root
    privileged: true
    cap_add:
      - NET_ADMIN
    container_name: snort3
    env_file:
      - config.env
    volumes:
      - /usr/src:/usr/src
      - /lib/modules:/lib/modules
      - /usr/lib/modules:/usr/lib/modules
      - /etc/nngf/shared/:/shared
    pid: "service:firewall"
    network_mode: "host"
    depends_on:
      - fluent-bit-collector
      - firewall
    logging:
      driver: fluentd
      options:
        fluentd-async: "true"

  daemon:
    image: ${REGISTRY_BASE}/nngf/daemon:latest
    container_name: daemon
    restart: unless-stopped
    environment:
      API_KEY: ${API_KEY}
      CERT_PATH: /etc/nginx/ssl/live/$FQDN/fullchain.pem
      KEY_PATH : /etc/nginx/ssl/live/$FQDN/privkey.pem
      LISTEN_PORT: 443
      ENDPOINT_PREFIX: '/daemon'
      USE_TLS: yes
      SHARED_DAEMON_FOLDER: /shared
      SHARED_FW_FOLDER: /shared
    volumes:
      - /etc/nngf/certbot/conf/:/etc/nginx/ssl/:ro
      - /etc/nngf/shared/:/shared
      - /var/run/docker.sock:/var/run/docker.sock:rw
      - /etc/nngf/:/etc/nngf:rw
      - /etc/machine-id:/etc/machine-id:ro
      - /var/lib/dbus/machine-id:/var/lib/dbus/machine-id:ro

  frontend:
    image: ${REGISTRY_BASE}/nngf/nngf-front:latest
    restart: unless-stopped

  backend:
    image: ${REGISTRY_BASE}/nngf/backend:latest
    restart: unless-stopped
    environment:
      ADMIN_PASSWORD: ${ADMIN_PASSWORD}
    volumes:
      - backend-db:/var/www/db/

  certbot:
    restart: unless-stopped
    image: certbot/certbot:latest
    volumes:
      - /etc/nngf/certbot/www/:/var/www/certbot/:rw
      - /etc/nngf/certbot/conf/:/etc/letsencrypt/:rw
    entrypoint: "/bin/sh -c 'trap exit TERM; while :; do certbot renew; sleep 12h & wait \$\${!}; done;'"

  webserver:
    restart: unless-stopped
    image: nginx:1.19.6
    ports:
      - 80:80
      - 443:443
    volumes:
      - /etc/nngf/nginx/conf/:/etc/nginx/conf.d/:ro
      - /etc/nngf/certbot/www:/var/www/certbot/:ro
      - /etc/nngf/certbot/conf/:/etc/nginx/ssl/:ro
    depends_on:
      - frontend
      - backend
      - daemon

  database:
    image: yandex/clickhouse-server
    restart: unless-stopped
    #network_mode: host
    ports:
      - "8123:8123"
      - "9000:9000"
      - "9009:9009"
    volumes:
      - clickhouse-data:/var/lib/clickhouse
      - /etc/nngf/clickhouse/init-defaults.sh:/docker-entrypoint-initdb.d/init-defaults.sh:ro
    environment:
      # Default user and database will be created using init-defaults.sh script
      CLICKHOUSE_USER: ${CLICKHOUSE_USER}
      CLICKHOUSE_PASSWORD: ${CLICKHOUSE_PASSWORD}
    hostname: clickhouse.localhost
    ulimits:
      nproc: 65535
      nofile:
       soft: 262144
       hard: 262144

  fluent-bit-server:
    network_mode: host
    image: fluent/fluent-bit
    restart: unless-stopped
    volumes:
      - /etc/nngf/fluent-bit/server-fluent-bit.conf:/fluent-bit/etc/fluent-bit.conf
      - /etc/nngf/fluent-bit/server-parsers.conf:/fluent-bit/etc/parsers.conf
      - /etc/nngf/fluent-bit/override_time.lua:/fluent-bit/etc/override_time.lua
    ports:
      - "1514:1514"

  fluent-bit-collector:
    image: fluent/fluent-bit
    restart: unless-stopped
    volumes:
      - /etc/nngf/fluent-bit/collector-fluent-bit.conf:/fluent-bit/etc/fluent-bit.conf
    ports:
      - "24224:24224"
      - "24224:24224/udp"

volumes:
  backend-db:
  clickhouse-data:

_EOF_

 mkdir -p /etc/nngf/nginx/conf
 cat > /etc/nngf/nginx/conf/nginx.conf << _EOF_
server {
    listen 80;
    server_name _;
    server_tokens off;
    client_max_body_size 20M;

    location /.well-known/acme-challenge/ {
        root /var/www/certbot;
    }

    location / {
        return 301 https://\$host\$request_uri;
    }

}

server {
    listen 443 default_server ssl http2;
    listen [::]:443 ssl http2;
    server_name _;

    ssl_certificate /etc/nginx/ssl/live/$FQDN/fullchain.pem;
    ssl_certificate_key /etc/nginx/ssl/live/$FQDN/privkey.pem;

    location / {
      try_files $uri $uri/ @frontend;
    }


    location @frontend {
        proxy_set_header X-Forwarded-Proto https;
        proxy_set_header X-Url-Scheme \$scheme;
        proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;
        proxy_set_header Host \$http_host;
        proxy_redirect off;
        proxy_pass   http://frontend:80;
    }


    location /api {
        proxy_set_header X-Forwarded-Proto https;
        proxy_set_header X-Url-Scheme \$scheme;
        proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;
        proxy_set_header Host \$http_host;
        proxy_redirect off;
        proxy_pass   http://backend:80;
    }

    location /daemon {
        proxy_set_header X-Forwarded-Proto https;
        proxy_set_header X-Url-Scheme \$scheme;
        proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;
        proxy_set_header Host \$http_host;
        proxy_redirect off;
        proxy_pass   https://daemon:443;
    }
}
_EOF_

/usr/local/bin/docker-compose -f /etc/nngf/docker-compose.yml pull
/usr/local/bin/docker-compose -f /etc/nngf/docker-compose.yml up -d
}

UNATTENDED=0

for i in "$@"
do
case $i in
    -a)
    UNATTENDED=1
    FQDN=$(hostname -f)
    n=3
    ;;
    *)
            # unknown option
    ;;
esac
done

# Main proc
if [ $UNATTENDED = 0 ]; then
  echo -n "Enter FQDN for certificate request(${FQDN}):"
  read -r FQDN_E
  FQDN="${FQDN_E:-${FQDN}}"

  echo '1) Install controller'
  echo '2) Install service'
  echo '3) Install controller+service'
  echo
  echo -n 'Enter installation type(3):'
  read -r n
  n="${n:-3}"
fi

case $n in
  1) INSTALL_CONTROLLER=1; INSTALL_SERVICE=0;;
  2) INSTALL_CONTROLLER=0; INSTALL_SERVICE=1;;
  3) INSTALL_CONTROLLER=1; INSTALL_SERVICE=1;;
  *) echo "invalid option"; exit 1;;
esac

if [ $INSTALL_CONTROLLER = 1 ]; then
  if [ $UNATTENDED = 0 ]; then
    echo -n "Enter ADMIN password for UI(${ADMIN_PASSWORD}):"
    read -r ADMIN_PASSWORD_E
  fi
  ADMIN_PASSWORD="${ADMIN_PASSWORD_E:-${ADMIN_PASSWORD}}"
fi

request_cert

if [ $INSTALL_CONTROLLER = 1 ] && [ $INSTALL_SERVICE = 1 ]; then
  install_all

  echo "Authorization https://${FQDN}/
    admin@email.com/${ADMIN_PASSWORD}
    user@email.com/user
    operator@email.com/operator"
  exit 0
fi

if [ $INSTALL_CONTROLLER = 1 ]; then
  install_controller

  echo "Authorization https://${FQDN}/
    admin@email.com/${ADMIN_PASSWORD}
    user@email.com/user
    operator@email.com/operator"

  exit 0
fi

if [ $INSTALL_SERVICE = 1 ]; then
  install_service
fi