#!/bin/sh

vault secrets enable pki
vault secrets tune -max-lease-ttl=87600h pki

vault write -field=certificate pki/root/generate/internal \
        common_name="ego.io" \
        ttl=87600h > CA_cert.crt

vault write pki/config/urls \
        issuing_certificates="https://127.0.0.1:8200/v1/pki/ca" \
        crl_distribution_points="https://127.0.0.1:8200/v1/pki/crl"

vault secrets enable -path=pki_int pki
vault secrets tune -max-lease-ttl=43800h pki_int

vault write -format=json pki_int/intermediate/generate/internal \
        common_name="ego.io Intermediate Authority" \
        | jq -r '.data.csr' > pki_intermediate.csr

vault write -format=json pki/root/sign-intermediate csr=@pki_intermediate.csr \
        format=pem_bundle ttl="43800h" \
        | jq -r '.data.certificate' > intermediate.cert.pem

vault write pki_int/intermediate/set-signed certificate=@intermediate.cert.pem

vault write pki_int/roles/ego.io \
  allowed_domains="ego.io" \
  allow_subdomains=true \
  generate_lease=true \
  max_ttl="720h"

vault write pki_int/issue/ego.io \
  common_name="catalog.service.ego.io" \
  ttl="24h" | tee certs.txt


# CONFIGURE CONSUL
mkdir -p /opt/consul/agent-certs

grep -Pzo "(?s)(?<=certificate)[^\-]*.*?END CERTIFICATE[^\n]*\n" certs.txt | sed 's/^\s*-/-/g' > /opt/consul/agent-certs/agent.crt
grep -Pzo "(?s)(?<=private_key)[^\-]*.*?END RSA PRIVATE KEY[^\n]*\n" certs.txt | sed 's/^\s*-/-/g' > /opt/consul/agent-certs/agent.key
grep -Pzo "(?s)(?<=issuing_ca)[^\-]*.*?END CERTIFICATE[^\n]*\n" certs.txt | sed 's/^\s*-/-/g' > /opt/consul/agent-certs/ca.crt
## FIXME ^^ invalid pattern flag...

