#!/bin/sh

# Setup environment variables for Vault
export VAULT_ADDR="http://$VAULT_DEV_LISTEN_ADDRESS"
export VAULT_TOKEN=$VAULT_DEV_ROOT_TOKEN_ID
CAPIF_HOSTNAME="${CAPIF_HOSTNAME:-capifcore}"

echo "CAPIF_HOSTNAME: $CAPIF_HOSTNAME"
echo "VAULT_ADDR: $VAULT_ADDR"
echo "VAULT_TOKEN: $VAULT_TOKEN"

vault secrets enable pki

# Generate a root CA
vault secrets tune -max-lease-ttl=87600h pki

vault write -field=certificate pki/root/generate/internal \
     common_name="capif" \
     issuer_name="root-2023" \
     ttl=87600h > root_2023_ca.crt

vault write pki/config/urls \
     issuing_certificates="$VAULT_ADDR/v1/pki/ca" \
     crl_distribution_points="$VAULT_ADDR/v1/pki/crl"

# Generate an intermediate CA
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="capif Intermediate Authority" \
     issuer_name="capif-intermediate" \
    | jq -r '.data.csr' > pki_intermediate.csr

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

# Configure the intermediate CA
vault write pki_int/intermediate/set-signed certificate=@capif_intermediate.cert.pem

# Configure the role for the intermediate CA
vault write pki_int/roles/my-ca use_csr_common_name=false require_cn=true use_csr_sans=false allowed_domains=$CAPIF_HOSTNAME allow_any_name=true allow_bare_domains=true allow_glob_domains=true allow_subdomains=true max_ttl=4300h

# Generate a certificate
openssl genrsa -out ./server.key 2048


COUNTRY="ES"                # 2 letter country-code
STATE="Madrid"            # state or province name
LOCALITY="Madrid"        # Locality Name (e.g. city)
ORGNAME="Telefonica I+D" # Organization Name (eg, company)
ORGUNIT="Innovation"                  # Organizational Unit Name (eg. section)
COMMONNAME="$CAPIF_HOSTNAME"
EMAIL="inno@tid.es"    # certificate's email address
# optional extra details
CHALLENGE=""                # challenge password
COMPANY=""                  # company name

# DAYS="-days 365"

# create the certificate request
cat <<__EOF__ | openssl req -new $DAYS -key ./server.key -out ./server.csr
$COUNTRY
$STATE
$LOCALITY
$ORGNAME
$ORGUNIT
$COMMONNAME
$EMAIL
$CHALLENGE
$COMPANY
__EOF__


vault write -format=json pki_int/sign/my-ca  format=pem_bundle ttl="43000h" csr=@server.csr common_name="$CAPIF_HOSTNAME" | jq -r '.data.issuing_ca as $issuing_ca | .data.certificate as $certificate | [$issuing_ca, $certificate]' > cert_data.json

jq -r '.[0]' cert_data.json > root_ca.crt.pem
jq -r '.[1]' cert_data.json > server_certificate.crt.pem

openssl x509 -pubkey -noout -in server_certificate.crt.pem  > server_certificate_pub.pem

# Concatenate the root and intermediate CA certificates
cat > certificados_concatenados.crt << EOF
$(cat "root_2023_ca.crt")
$(cat "root_ca.crt.pem")
EOF

vault kv put secret/ca ca=@certificados_concatenados.crt

vault kv put secret/server_cert cert=@server_certificate.crt.pem

vault kv put secret/server_cert/pub pub_key=@server_certificate_pub.pem

vault kv put secret/server_cert/private key=@server.key

POLICY_NAME="my-policy"
POLICY_FILE="my-policy.hcl"
TOKEN_ID="read-ca-token"

# Create a policy to read the CA
echo "path \"secret/data/ca\" {
  capabilities = [\"read\"]
}" > "$POLICY_FILE"

vault policy write "$POLICY_NAME" "$POLICY_FILE"

# Create a token with the policy
TOKEN=$(vault token create -id="$TOKEN_ID" -policy="$POLICY_NAME" -format=json | jq -r '.auth.client_token')

echo "Generated Token:"
echo "$TOKEN"