#!/bin/bash

# usage
# ./enroll_device_certificate.sh 192.168.122.59 device1_guid SuperAdmin.p12 foo123

if [ $# -ne 4 ]
    then
        echo 'usage: ./enroll_device_certificate.sh 192.168.122.59 device1_guid SuperAdmin.p12 foo123'
        exit 1
fi

EJBCA_HOST="$1"
DEVICE_DN="$2"
ADMINP12="$3"
ADMINP12PASS="$4"

openssl req -nodes -newkey rsa:2048 -keyout "$DEVICE_DN.key" \
          -out enroll.csr -subj "/CN=$DEVICE_DN" 
#ls -l
REQ_CSR="$(while read line; do printf "%s" "$line"; done < enroll.csr)"
#echo $REQ_CSR

REQ_CSR="$(echo $REQ_CSR | sed "s|-----BEGIN CERTIFICATE REQUEST-----||g")"
REQ_CSR="$(echo $REQ_CSR | sed "s|-----END CERTIFICATE REQUEST-----||g")"
request_body="{
  \"certificate_request\": \"$REQ_CSR\",
  \"certificate_profile_name\": \"DeviceCertProfile\",
  \"end_entity_profile_name\": \"DeviceEndEntityProfile\",
  \"certificate_authority_name\": \"IssuerCA\",
  \"username\": \"$DEVICE_DN\",
  \"password\": \"foo123\",
  \"account_binding_id\": \"\",
  \"include_chain\": false
}"


echo $request_body

curl -X 'POST' -kvL \
  "https://$EJBCA_HOST/ejbca/ejbca-rest-api/v1/certificate/pkcs10enroll" \
  --cert-type P12 --cert "$ADMINP12:$ADMINP12PASS" \
  -H 'accept: application/json' \
  -H 'Content-Type: application/json' \
  -o enrolled.json \
  -d "$request_body"

cert_begin=$(awk -F 'certificate":"' '{print $2 ""}' enrolled.json)
echo $cert_begin
cert_end=$(awk -F '","serial_number"' '{print $1 ""}' <<<$cert_begin)
echo $cert_end

# printf '%s\n' 'first line' 'second line' 'third line' > file
enrolled_cert="-----BEGIN CERTIFICATE-----\n$cert_end\n-----END CERTIFICATE-----"
echo -en $enrolled_cert>enrolled_unformatted.pem

fold -w64 enrolled_unformatted.pem > "$DEVICE_DN.pem"

# sanity
openssl x509 -in "$DEVICE_DN.pem" -noout -text

