#!/bin/bash
#
# Proxy Service

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

config_proxy() {
  echo -ne "\n* Configuring /federated/apps/proxy container.."
  spin &
  SPINPID=$!

  DOMAIN_ARRAY=(${DOMAIN//./ })
  DOMAIN_FIRST=${DOMAIN_ARRAY[0]}
  DOMAIN_MIDDLE=${DOMAIN_ARRAY[1]}
  DOMAIN_LAST=${DOMAIN_ARRAY[2]}

  if [ ! -d "/federated/apps/proxy" ]; then
    mkdir -p /federated/apps/proxy/data/root/certs &> /dev/null
    cp /federated/apps/dns/data/etc/letsencrypt/archive/$DOMAIN_MIDDLE.$DOMAIN_LAST/fullchain1.pem /federated/apps/proxy/data/root/certs/$DOMAIN_MIDDLE.$DOMAIN_LAST.crt
    cp /federated/apps/dns/data/etc/letsencrypt/archive/$DOMAIN_MIDDLE.$DOMAIN_LAST/privkey1.pem /federated/apps/proxy/data/root/certs/$DOMAIN_MIDDLE.$DOMAIN_LAST.key
  fi

#  DOMAIN_ARRAY=(${DOMAIN//./ })
#  DOMAIN_FIRST=${DOMAIN_ARRAY[0]}
#  DOMAIN_LAST=${DOMAIN_ARRAY[1]}

cat > /federated/apps/proxy/docker-compose.yml <<EOF
services:
  proxy:
    image: jwilder/nginx-proxy:\${IMAGE_VERSION}
    container_name: proxy
    hostname: proxy.$DOMAIN
    restart: always
    networks:
      core:
        ipv4_address: 192.168.0.15
    ports:
      - "80:80"
      - "443:443"
    volumes:
      - /var/run/docker.sock:/tmp/docker.sock:ro
      - ./data/root/certs:/etc/nginx/certs
      - ./data/custom.conf:/etc/nginx/conf.d/custom.conf:ro
    env_file:
      - ./.env

networks:
  core:
    external: true
EOF

cat > /federated/apps/proxy/.env <<EOF
IMAGE_VERSION="1.1"
DEFAULT_HOST=www.$DOMAIN
EOF
chmod 600 /federated/apps/proxy/.env

cat > /federated/apps/proxy/data/custom.conf <<EOF
client_max_body_size 64000M;
EOF
 
kill -9 $SPINPID &> /dev/null
echo -ne "done."
}
start_proxy() {
  # Start service with command to make sure it's up before proceeding
  start_service "proxy" "nc -z 192.168.0.15 443 &> /dev/null"

  kill -9 $SPINPID &> /dev/null
  echo -ne "done."
}
