#!/bin/bash

# Read the input from the file
input=$(<tmp_certificate.txt)

# Use regex to extract the chain certificate, certificate, and private key
regex_issuing_ca="issuing_ca +-----BEGIN CERTIFICATE-----(.*)-----END CERTIFICATE-----"
regex_cert="certificate +-----BEGIN CERTIFICATE-----(.*)-----END CERTIFICATE-----"
regex_private_key="private_key +-----BEGIN RSA PRIVATE KEY-----(.*)-----END RSA PRIVATE KEY-----"

mkdir -p certs/

# Extract the chain certificate, certificate, and private key using regex
if [[ $input =~ $regex_issuing_ca ]]; then
  issuing_ca="-----BEGIN CERTIFICATE-----${BASH_REMATCH[1]}-----END CERTIFICATE-----"
  printf '%s' "$issuing_ca" > certs/cacert.pem
fi
if (( $(bc <<< "$(ls -lh certs/cacert.pem | awk '{print $5}' | sed 's/K$//') < 1") )); then
  echo "There is some problem with creating cacert.pem"
  exit 1
fi  

if [[ $input =~ $regex_cert ]]; then
  cert="-----BEGIN CERTIFICATE-----${BASH_REMATCH[1]}-----END CERTIFICATE-----"
  printf '%s' "$cert" | awk '/-----BEGIN CERTIFICATE-----/,/-----END CERTIFICATE-----/{print} {if ($0 ~ /-----END CERTIFICATE-----/) exit}' > certificate.pem
fi
if (( $(bc <<< "$(ls -lh certificate.pem | awk '{print $5}' | sed 's/K$//') < 1") )); then
  echo "There is some problem with creating certificate.pem"
  exit 1
fi  

if [[ $input =~ $regex_private_key ]]; then
  private_key="-----BEGIN RSA PRIVATE KEY-----${BASH_REMATCH[1]}-----END RSA PRIVATE KEY-----"
  printf '%s' "$private_key" > certs/serverkey.pem
fi
if (( $(bc <<< "$(ls -lh certs/serverkey.pem | awk '{print $5}' | sed 's/K$//') < 1") )); then
  echo "There is some problem with creating serverkey.pem"
  exit 1
fi  

cat certificate.pem > certs/servercert.pem
cat certs/cacert.pem >> certs/servercert.pem

echo "Files created: cacert.pem, servercert.pem, serverkey.pem"

CERTS_PATH=p81-$ENV_NAME-env-files/yarkon-gateway/certs/
aws s3 cp --recursive certs/ s3://$CERTS_PATH
