---
apiVersion: v1
kind: ConfigMap
metadata:
  name: vault-prepare-certs
  namespace: ocf-vault
  labels:
    io.kompose.service: api-invocation-logs
    app: capif
    app.kubernetes.io/name: capif
    app.kubernetes.io/instance: capif
data:
  vault-prepare-certs.sh: |-
     #!/bin/sh
    
     echo "install dependencies"
     apk add --no-cache jq openssl

     # Establecer las variables de entorno de Vault

     export VAULT_ADDR='http://vault-internal:8200'
     
     # In standalone's mode. Please use the root's token
     # or the token with the sufficient permissions
     # to execute the next commands in vault
     # otherwise, if use the vault as dev's mode. Just
     # type the token's dev.
     export VAULT_TOKEN=""
     export DOMAIN1=*.ocf.pre-production
     export DOMAIN2=*.ocf.validation
     export DOMAIN3=*.ocf.develop

     # local domains
     # export DOMAIN4=*.pre-prod.svc.cluster.local
     # export DOMAIN5=*.staging.svc.cluster.local
     # export DOMAIN6=*.developer.svc.cluster.local
     
     vault secrets enable pki
     
     echo "# Generar una CA en Vault #"
     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
    
     echo "# check root_2023_ca.crt #"
     cat root_2023_ca.crt
     
     vault write pki/config/urls \
          issuing_certificates="$VAULT_ADDR/v1/pki/ca" \
          crl_distribution_points="$VAULT_ADDR/v1/pki/crl"
     
     # # Generar una CA intermedia en Vault
     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
     
     echo "### content pki_intermediate.csr ###"
     cat pki_intermediate.csr
     
     # Firmar la CA intermedia con la CA raíz
     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
     
     # Configurar la CA intermedia en Vault
     vault write pki_int/intermediate/set-signed certificate=@capif_intermediate.cert.pem
     
     #Crear rol en Vault
     vault write pki_int/roles/my-ca use_csr_common_name=false require_cn=false allowed_domains="*" allow_any_name=true allow_bare_domains=true allow_glob_domains=true allow_subdomains=true max_ttl=4300h ttl=4300h
     
     # Emitir un certificado firmado por la CA intermedia
     # vault write -format=json pki_int/issue/my-ca \
     #   common_name="nginx.mon.svc.cluster.local" \
     #   format=pem_bundle ttl="438h" \
     #   | jq -r '.data.certificate' > ccf_cert.crt.pem \
     #   && jq -r '.data.issuing_ca' > root_ca.crt.pem \
     #   && jq -r '.data.private_key' > private_key.pem
     
     #   vault write -format=json pki_int/issue/my-ca \
     #   common_name="nginx.mon.svc.cluster.local" \
     #   format=pem_bundle ttl="438h" \
     #   | jq -r '.data.private_key as $private_key | .data.issuing_ca as $issuing_ca | .data.certificate as $certificate | [$private_key, $issuing_ca, $certificate]' > cert_data.json
     
     
     #Create CSR
     openssl genrsa -out ./server.key 2048
     
     cat > ./foo.cnf <<EOF
     [ req ]
     distinguished_name = req_distinguished_name
     req_extensions = v3_req
     
     [ req_distinguished_name ]
     countryName = \$ENV::COUNTRY
     countryName_default = \$ENV::COUNTRY
     stateOrProvinceName = \$ENV::STATE
     stateOrProvinceName_default = \$ENV::STATE
     localityName = \$ENV::LOCALITY
     localityName_default = \$ENV::LOCALITY
     organizationName = \$ENV::ORGNAME
     organizationName_default = \$ENV::ORGNAME
     organizationalUnitName  = \$ENV::ORGUNIT
     organizationalUnitName_default  = \$ENV::ORGUNIT
     commonName = capif
     commonName_max  = 64
     emailAddress = Email Address
     emailAddress_max = 64
     emailAddress_default = \$ENV::EMAIL
     
     [ v3_req ]
     subjectAltName = @alt_names
     
     [alt_names]
     DNS.1 = \$ENV::DOMAIN1
     DNS.2 = \$ENV::DOMAIN2
     DNS.3 = \$ENV::DOMAIN3
     EOF

     export COUNTRY=ES                # 2 letter country-code
     export STATE=Madrid            # state or province name
     export LOCALITY=Madrid        # Locality Name (e.g. city)
     export ORGNAME="Telefonica I+D" # Organization Name (eg, company)
     export ORGUNIT=Innovation                  # Organizational Unit Name (eg. section)
     export COMMONNAME="nginx.mon.svc.cluster.local"
     export EMAIL=inno@tid.es    # certificate's email address
     # optional extra details
     CHALLENGE=""                # challenge password
     COMPANY=""                  # company name
     
     # DAYS="-days 365"
     
     # create the certificate request
     openssl req -new $DAYS -batch -key ./server.key -out ./server.csr -config ./foo.cnf -extensions v3_req
     
     echo "### verify the Subject Alternative Name (SAN) ###"
     openssl req -text -noout -verify -in ./server.csr | grep 'DNS'


     #cat <<__EOF__ | openssl req -new $DAYS -nodes -keyout client.key -out client.csr
     #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/issue/my-ca \
     #   csr=@server.csr \
     #   format=pem_bundle ttl="438h" \
     #   | jq -r '.data.private_key as $private_key | .data.issuing_ca as $issuing_ca | .data.certificate as $certificate | [$private_key, $issuing_ca, $certificate]' > cert_data.json
     
     vault write -format=json pki_int/sign/my-ca  format=pem_bundle ttl="43000h" csr=@server.csr | 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
     echo "### content root_ca.crt.pem ###"
     cat root_ca.crt.pem

     echo "### content server_certificate.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
     
     #vault kv put secret/ca ca=@root_helm.pem root_2023_ca.crt
     
     #cat root_2023_ca.crt root_2023_ca.crt > ca.crt
     
     cat > certificados_concatenados.crt << EOF
     $(cat "root_2023_ca.crt")
     $(cat "root_ca.crt.pem")
     EOF
     echo "### content of root_2023_ca.crt ###"
     cat root_2023_ca.crt

     echo "### content of root_ca.crt.pem ###"
     cat root_ca.crt.pem

     echo "### content of certificados_concatenados.crt ###"
     cat certificados_concatenados.crt
     
     # vault kv put secret/ca ca=@root_2023_ca.crt

     echo "### enable secrets kv ###"
     vault secrets enable -path=secret -version=2 kv

     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"
     
     # Crear la política en Vault
     #echo "path \"secret/data/ca\" {
     #  capabilities = [\"read\"]
     #}" > "$POLICY_FILE"
     
     #vault policy write "$POLICY_NAME" "$POLICY_FILE"
     
     # Generar un nuevo token y asignar la política
     #TOKEN=$(vault token create -id="$TOKEN_ID" -policy="$POLICY_NAME" -format=json | jq -r '.auth.client_token')
     
     #echo "Token generado:"
     #echo "$TOKEN"
---

apiVersion: batch/v1
kind: Job
metadata:
  name: vault-pki
  namespace: ocf-vault
  labels:
    io.kompose.service: vault-pki
    app: capif
    app.kubernetes.io/name: capif
    app.kubernetes.io/instance: capif
spec:
  template:
    spec:
      containers:
      - name: vault-pki
        image: docker.io/hashicorp/vault:1.15.1
        command: ["./vault-prepare-certs.sh"]
        volumeMounts:
          - name: vault-prepare-certs
            mountPath: vault-prepare-certs.sh
            subPath: vault-prepare-certs.sh
      restartPolicy: Never
      volumes:
      - name:  vault-prepare-certs
        configMap:
          name: vault-prepare-certs
          defaultMode: 0777
          items:
          - key: "vault-prepare-certs.sh"
            path: "vault-prepare-certs.sh"
  backoffLimit: 4
