#!/bin/bash
CERTS_FOLDER="/usr/src/app/register_service"
cd $CERTS_FOLDER

VAULT_ADDR="http://$VAULT_HOSTNAME:$VAULT_PORT"
VAULT_TOKEN=$VAULT_ACCESS_TOKEN

curl  -k -retry 30 \
    --retry-all-errors \
    --connect-timeout 5 \
    --max-time 10 \
    --retry-delay 10 \
    --retry-max-time 300 \
    --header "X-Vault-Token: $VAULT_TOKEN" \
    --request GET "$VAULT_ADDR/v1/secret/data/server_cert/private" 2>/dev/null | jq -r '.data.data.key' -j > $CERTS_FOLDER/server.key

openssl req -x509 \
            -sha256 -days 356 \
            -nodes \
            -newkey rsa:2048 \
            -subj "/CN=register/C=ES/L=Madrid" \
            -keyout /usr/src/app/register_service/registerCA.key -out /usr/src/app/register_service/registerCA.crt

openssl genrsa -out /usr/src/app/register_service/register_key.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="register"
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 /usr/src/app/register_service/register_key.key -out /usr/src/app/register_service/register.csr
$COUNTRY
$STATE
$LOCALITY
$ORGNAME
$ORGUNIT
$COMMONNAME
$EMAIL
$CHALLENGE
$COMPANY
__EOF__

openssl x509 -req -in /usr/src/app/register_service/register.csr -CA /usr/src/app/register_service/registerCA.crt -CAkey /usr/src/app/register_service/registerCA.key  -CAcreateserial -out /usr/src/app/register_service/register_cert.crt -days 365 -sha256

cd /usr/src/app/
python3 -m register_service