# Dainsy Opc-Ua authentication certificate tool

if [[ $(id -u) -ne 0 ]] ; then echo "Please run with sudo or run as root" ; exit 1 ; fi

if [ -z "$1" ]
  then
    echo "ERROR: Please provides the common-name when calling the certificate tool"
    echo "Example: admin@localhost: ~$ sudo /etc/app-opcua/server_auth_pki/tools/create-self-signed-auth client1"
    exit 1
fi

CN="$1"

# Define where to store the generated certs and metadata.
DIR="$(pwd)/cert-${CN}"

# Optional: Ensure the target directory exists and is empty.
rm -rf "${DIR}"
mkdir -p "${DIR}"

# Create the openssl configuration file. This is used for both generating
# the certificate as well as for specifying the extensions. It aims in favor
# of automation, so the DN is encoding and not prompted.
cat > "${DIR}/openssl.cnf" << EOF
[req]
days                   = 365
serial                 = 0
distinguished_name     = req_distinguished_name
x509_extensions        = v3_ca
prompt                 = no

[req_distinguished_name]
countryName            = CA
stateOrProvinceName    = Quebec
localityName           = Montreal
organizationName       = Resologi
organizationalUnitName = Dainsy
commonName             = ${CN}
0.emailAddress         = info@resologi.com

[ v3_ca ]
# The extentions to add to a self-signed cert
subjectKeyIdentifier   = hash
authorityKeyIdentifier = keyid:always,issuer:always
basicConstraints       = CA:TRUE
keyUsage               = digitalSignature, nonRepudiation, keyEncipherment, dataEncipherment, keyAgreement, keyCertSign
subjectAltName         = DNS:${HOSTNAME}, email:info@resologi.com
issuerAltName          = issuer:copy

EOF

openssl req \
  -newkey rsa:4096 \
  -days 365 \
  -nodes \
  -x509 \
  -keyout "${DIR}/${CN}_key.pem" \
  -out "${DIR}/${CN}.pem" \
  -config "${DIR}/openssl.cnf"

# Convert certificate from PEM format to DER format, to use the certificate with UAExpert
openssl x509 -in "${DIR}/${CN}.pem" -outform der -out "${DIR}/${CN}.der"

# Export certificate information as text
openssl x509 -in "${DIR}/${CN}.pem" -noout -text > "${DIR}/${CN}.txt"

# Produce PFX certificate containing certificate and key to use on windows based systems
openssl pkcs12 -passout pass: -export -out "${DIR}/${CN}.pfx" -inkey "${DIR}/${CN}_key.pem" -in "${DIR}/${CN}.pem"

# Gives read access to certificate folder
chmod +r ${DIR} -R

# Deploy certificate on the opcua server trusted collection
cp "${DIR}/${CN}.der" "/etc/app-opcua/server_auth_pki/trusted/certs/"

echo "The client certificate has been copied to the opcua server trusted certificates folder /etc/app-opcua/server_auth_pki/trusted/certs/"
echo "To be effective, please restart the opcua server (systemctl restart app-opcua-srv)"
echo "All produced files you will need for the opcua client are available in this folder: ./cert-${CN}/"
