#!/bin/bash
#
# Caddy Service

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

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

  if [ ! -d "/federated/apps/caddy" ]; then
    mkdir -p /federated/apps/caddy/data/data
    mkdir -p /federated/apps/caddy/data/srv
    mkdir -p /federated/apps/caddy/data/etc/caddy
  fi

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

services:
  caddy:
    image: federatedcomputer/caddy:\${IMAGE_VERSION}
    container_name: caddy
    hostname: caddy.$DOMAIN
    domainname: $DOMAIN
    restart: always
    networks:
      federated:
        ipv4_address: 172.99.0.31
    extra_hosts:
      - "gitea.$DOMAIN:$EXTERNALIP"
    env_file:
      - ./.env
    volumes:
      - ./data/srv:/srv
      - ./data/etc/caddy/Caddyfile:/etc/caddy/Caddyfile
      - ./data/data:/data
    labels:
      - "traefik.enable=true"
      - "traefik.http.routers.caddy.rule=Host(\`caddy.$DOMAIN\`,\`blog.$DOMAIN\`)"
      - "traefik.http.routers.caddy.entrypoints=websecure"
      - "traefik.http.routers.caddy.tls.certresolver=letsencrypt"

networks:
  federated:
    external: true
EOF

cat > /federated/apps/caddy/.env <<EOF
IMAGE_VERSION="latest"
EOF
chmod 600 /federated/apps/caddy/.env

cat > /federated/apps/caddy/data/etc/caddy/Caddyfile <<EOF
$DOMAIN:80 {
  root * /srv/www/public
  file_server
}
caddy.$DOMAIN:80 {
  root * /srv/www/public
  file_server
  route /webhook {
    webhook {
      repo https://gitea.$DOMAIN/gitea/www
      type github
      secret $WEBHOOK_SECRET
      submodule
      token $GITEA_TOKEN_1
      path www
      branch master
    }
  }
}
blog.$DOMAIN:80 {
  root * /srv/blog/public
  file_server
  route /webhook {
    webhook {
      repo https://gitea.$DOMAIN/gitea/blog
      type github
      secret $WEBHOOK_SECRET
      submodule
      token $GITEA_TOKEN_1
      path blog
      branch master
    }
  }
}
documentation.$DOMAIN:80 {
  root * /srv/documentation/public
  file_server
  route /webhook {
    webhook {
      repo https://gitea.$DOMAIN/gitea/documentation
      type github
      secret $WEBHOOK_SECRET
      submodule
      token $GITEA_TOKEN_1
      path documentation
      branch master
    }
  }
}
EOF

kill -9 $SPINPID &> /dev/null
echo -ne "done."
}
start_caddy() {
  # Start service with command and retry amount to make sure it's up before proceeding
  start_service "caddy" "nc -z 172.99.0.31 80 &> /dev/null" "7"

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