#!/bin/bash
#
# Nginx Service

PATH=$HOME/.docker/cli-plugins:/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
get_appvars

config_nginx() {
  echo -ne "\n* Configuring /federated/apps/nginx container.."

  if [ ! -d "/federated/apps/nginx" ]; then
    mkdir -p /federated/apps/nginx/data/etc/nginx/conf.d
  fi

cat > /federated/apps/nginx/docker-compose.yml <<EOF
services:
  nginx:
    image: nginx:latest
    container_name: nginx
    hostname: nginx.$DOMAIN
    restart: always
    networks:
      core:
        ipv4_address: 192.168.0.40
    volumes:
      - ./data/etc/nginx/conf.d/matrix.conf:/etc/nginx/conf.d/matrix.conf
    labels:
      - "traefik.enable=true"
      - "traefik.http.routers.nginx.rule=Host(\`matrix.$DOMAIN\`)"
      - "traefik.http.routers.nginx.entrypoints=websecure"
      - "traefik.http.routers.nginx.tls.certresolver=letsencrypt"

networks:
  core:
    external: true
EOF

cat > /federated/apps/nginx/data/etc/nginx/conf.d/matrix.conf <<EOF
server { listen 80 default_server;

  server_name    matrix.$DOMAIN;

  location / {
    proxy_pass http://192.168.0.19:8008;
    proxy_set_header X-Forwarded-For \$remote_addr;
    client_max_body_size 128m;
  }

  location /_matrix {
    proxy_pass http://192.168.0.19:8008;
    proxy_set_header X-Forwarded-For \$remote_addr;
    client_max_body_size 128m;
  }

  location /.well-known/matrix/server {
    access_log off;
    add_header Access-Control-Allow-Origin *;
    default_type application/json;
    return 200 '{"m.server": "matrix.$DOMAIN:443"}';
  }

  location /.well-known/matrix/client {
    access_log off;
    add_header Access-Control-Allow-Origin *;
    default_type application/json;
    return 200 '{"m.homeserver": {"base_url": "https://matrix.$DOMAIN"}}';
  }
}
EOF
 
echo -ne "done."
}
start_nginx() {
  # Start service with command to make sure it's up before proceeding
  start_service "nginx" "nc -z 192.168.0.40 80 &> /dev/null" "7"

  echo -ne "done."
}
