#!/usr/bin/env ./sshtool

PKI=deuxfleurs/cluster/$CLUSTER
YEAR=$(date +%Y)

cmd mkdir -p /var/lib/nomad/pki /var/lib/consul/pki

for file in consul-ca.crt consul$YEAR.crt consul$YEAR.key \
	consul$YEAR-client.crt consul$YEAR-client.key
do
	if pass $PKI/$file >/dev/null; then
		write_pass $PKI/$file /var/lib/consul/pki/$file
		cmd chown consul:root /var/lib/consul/pki/$file
	fi
done

cmd systemctl restart consul
cmd sleep 10

for file in nomad-ca.crt nomad$YEAR.crt nomad$YEAR.key \
	nomad$YEAR-client.crt nomad$YEAR-client.key \
	consul$YEAR.crt consul$YEAR-client.crt consul$YEAR-client.key
do
	if pass $PKI/$file >/dev/null; then
		write_pass $PKI/$file /var/lib/nomad/pki/$file
		cmd "chown \$(stat -c %u /var/lib/nomad) /var/lib/nomad/pki/$file"
	fi
done

cmd systemctl restart nomad

set_env CONSUL_HTTP_ADDR=https://localhost:8501
set_env CONSUL_CACERT=/var/lib/consul/pki/consul-ca.crt
set_env CONSUL_CLIENT_CERT=/var/lib/consul/pki/consul$YEAR-client.crt
set_env CONSUL_CLIENT_KEY=/var/lib/consul/pki/consul$YEAR-client.key

cmd "consul kv put secrets/consul/consul-ca.crt - < /var/lib/consul/pki/consul-ca.crt"
cmd "consul kv put secrets/consul/consul.crt - < /var/lib/consul/pki/consul$YEAR.crt"
cmd "consul kv put secrets/consul/consul-client.crt - < /var/lib/consul/pki/consul$YEAR-client.crt"
cmd "consul kv put secrets/consul/consul-client.key - < /var/lib/consul/pki/consul$YEAR-client.key"

cmd "consul kv put secrets/nomad/nomad-ca.crt - < /var/lib/nomad/pki/nomad-ca.crt"
cmd "consul kv put secrets/nomad/nomad.crt - < /var/lib/nomad/pki/nomad$YEAR.crt"
cmd "consul kv put secrets/nomad/nomad-client.crt - < /var/lib/nomad/pki/nomad$YEAR-client.crt"
cmd "consul kv put secrets/nomad/nomad-client.key - < /var/lib/nomad/pki/nomad$YEAR-client.key"