#!/bin/sh

# Establecer las variables de entorno de Vault

export VAULT_ADDR='http://0.0.0.0:8200'
export VAULT_TOKEN="dev-only-token"

vault secrets enable pki

# 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

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

# 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=true use_csr_sans=false allowed_domains=capifcore 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="capifcore" \
#   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="capifcore" \
#   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


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="capifcore"
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 -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 common_name="capifcore" | 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

# Guardar la clave privada en Vault

#vault kv put secret/ca ca=@root_ca.crt.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


# vault kv put secret/ca ca=@root_2023_ca.crt
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"