#!/bin/bash
#
# Traefik Service

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

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

  if [ ! -d "/federated/apps/traefik" ]; then
    mkdir -p /federated/apps/traefik/data/letsencrypt
  fi

TRAEFIK_HTTPAUTH_STRING=$(echo `htpasswd -nb admin $ADMINPASS` | sed -e s/\\$/\\$\\$/g)

cat > /federated/apps/traefik/docker-compose.yml <<EOF
version: "3.7"

services:
  traefik:
    image: traefik:\${IMAGE_VERSION}
    container_name: traefik
    hostname: traefik.$DOMAIN
    domainname: $DOMAIN
    restart: always
    networks:
      federated:
        ipv4_address: 172.99.0.13
    command:
      # Tell Traefik to discover containers using the Docker API
      - --providers.docker=true
      # Enable the Trafik dashboard
      - --api.dashboard=true
      # Set up LetsEncrypt
      - --certificatesresolvers.letsencrypt.acme.dnschallenge=true
      - --certificatesresolvers.letsencrypt.acme.dnschallenge.provider=pdns
      - --certificatesresolvers.letsencrypt.acme.email=hostmaster@$DOMAIN
      - --certificatesresolvers.letsencrypt.acme.storage=/letsencrypt/acme.json
      - --certificatesresolvers.letsencrypt.acme.dnschallenge.DisablePropagationCheck=true
      # --certificatesresolvers.letsencrypt.acme.caserver=https://acme-staging-v02.api.letsencrypt.org/directory
      # Added HTTP challenge
      - --certificatesresolvers.httpresolver.acme.httpchallenge=true
      - --certificatesresolvers.httpresolver.acme.httpchallenge.entrypoint=web
      #- "--certificatesresolvers.httpresolver.acme.caserver=https://acme-staging-v02.api.letsencrypt.org/directory"
      - --certificatesresolvers.httpresolver.acme.email=hostmaster@$DOMAIN
      - --certificatesresolvers.httpresolver.acme.storage=/letsencrypt/httpacme.json
      - --log.level=DEBUG
      # Set up an insecure listener that redirects all traffic to HTTPS
      - --entrypoints.web.address=:80
      - --entrypoints.websecure.address=:443
      - --entrypoints.web.http.redirections.entrypoint.to=websecure
      - --entrypoints.web.http.redirections.entrypoint.scheme=https
      # Set up the TLS configuration for our websecure listener
      - --entrypoints.websecure.http.tls=true
      - --entrypoints.websecure.http.tls.certResolver=letsencrypt
      - --entrypoints.websecure.http.tls.domains[0].main=$DOMAIN
      - --entrypoints.websecure.http.tls.domains[0].sans=*.$DOMAIN
    env_file:
      - ./.env
    ports:
      - 80:80
      - 443:443
    volumes:
      - /var/run/docker.sock:/var/run/docker.sock:ro
      - ./data/letsencrypt:/letsencrypt
    labels:
      - "traefik.enable=true"
      - "traefik.http.routers.traefik.rule=Host(\`traefik.$DOMAIN\`)"
      - "traefik.http.routers.traefik.entrypoints=websecure"
      - "traefik.http.routers.traefik.tls.certresolver=letsencrypt"
      - "traefik.http.routers.traefik.service=api@internal"
      - "traefik.http.routers.traefik.middlewares=strip"
      - "traefik.http.middlewares.strip.stripprefix.prefixes=/traefik"
      - "traefik.http.routers.traefik.middlewares=traefik-auth"
      - "traefik.http.middlewares.traefik-auth.basicauth.users=$TRAEFIK_HTTPAUTH_STRING"

networks:
  federated:
    external: true
EOF

PDNS_APIKEY=`grep PDNS_api_key /federated/apps/pdns/.env | awk -F= '{ print $2 }'`

cat > /federated/apps/traefik/.env <<EOF
IMAGE_VERSION="v2.10.1"
PDNS_API_KEY=$PDNS_APIKEY
PDNS_API_URL=http://pdns.$DOMAIN:8081
EOF
chmod 600 /federated/apps/traefik/.env

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

start_traefik() {
  echo -ne "\n* Starting /federated/apps/traefik service.."

  spin &
  SPINPID=$!

  if [ $DEBUG ]; then
    # Start /federated/apps/traefik with output to console for debug
    docker-compose -f /federated/apps/traefik/docker-compose.yml -p traefik up
    [ $? -eq 0 ] && echo -ne "done.\n" || fail "There was a problem starting service /federated/apps/traefik"
  else
    # Start /federated/apps/traefik with output to /dev/null
    docker-compose -f /federated/apps/traefik/docker-compose.yml -p traefik up -d &> /dev/null

    # Keep trying to see that certificates are generated
    RETRY="20"
    while [ $RETRY -gt 0 ]; do
      traefik-certs-dumper file --version v2 --source /federated/apps/traefik/data/letsencrypt/acme.json --dest /federated/certs &> /dev/null

      # Check if certs are generated
      ls /federated/certs/private/$DOMAIN.key /federated/certs/certs/$DOMAIN.crt &> /dev/null
      if [ $? -eq 0 ]; then
        kill -9 $SPINPID &> /dev/null
        echo -ne "done."
        break
      else
        if [ "$RETRY" == 1 ]; then
          docker-compose -f /federated/apps/traefik/docker-compose.yml -p traefik down &> /dev/null
          fail "There was a problem starting service /federated/apps/traefik\nCheck the output of 'docker logs traefik' or turn on\ndebug with -d"
        fi
        ((RETRY--))
        sleep 9
      fi
    done
  fi
}
