#!/bin/bash

set -e

. lib/common

LOCAL_CERTS_PATH=/etc/docker-auth/certs

certs_path="$SERVICE_CONFIGSTORE$LOCAL_CERTS_PATH"

mkdir -p "$certs_path"

(
    cd "$certs_path"
    openssl req -x509 -newkey rsa:2048 -new -nodes \
            -keyout privkey.pem -out fullchain.pem \
            -subj "/C=FR/ST=Paris/L=Paris/O=ACME/OU=IT Department/CN=[domain.tld]"
    chmod 600 privkey.pem
)

cat <<EOF | ini_merge

token:
  certificate: "$LOCAL_CERTS_PATH/fullchain.pem"
  key: "$LOCAL_CERTS_PATH/privkey.pem"

EOF


config-add "\
services:
  $TARGET_SERVICE_NAME:
    volumes:
      - \"$certs_path:$LOCAL_CERTS_PATH:ro\"
  $BASE_SERVICE_NAME:
    volumes:
      - \"$certs_path:$LOCAL_CERTS_PATH:ro\"
"


realm=$(cat "$SERVICE_CONFIGSTORE/etc/docker-auth/realm") || exit 1

relation-set registry-config "\
token:
  realm: \"$realm/auth\"
  service: \"Docker registry\"
  issuer: \"Acme auth server\"
  autoredirect: false
  rootcertbundle: \"$LOCAL_CERTS_PATH/fullchain.pem\"
"