@echo off

set OPENSSL=%~dp0%..\OpenSSL-Win64\bin
set OPENSSL_CONF=%~dp0%..\OpenSSL-Win64\bin\openssl.cfg

set cnta=0
set cntb=0

rem counts number of .cer files
for %%a in (*.cer) do (
  set /a cnta+=1
  set basename=%%~na
)

rem counts number of .key files
for %%A in (*.key) do (
  set /a cntb+=1
)

if %cnta%  NEQ 1 goto error
if %cntb%  NEQ 1 goto error

rem combine public certificates with private key
%OPENSSL%\openssl pkcs12 -export -out %basename%-combined.pfx -inkey *.key -in *.cer
if ERRORLEVEL 1  goto done

rem Certificate was combined
goto moveFiles

:error

if %cnta% EQU 0 echo Certificate file is missing. Please copy here the certificate file (has extension .cer)
if %cnta% GTR 1 echo More certificate files exist. Please check directory to ensure only one certificate file (.cer extension) is present

if %cntb% EQU 0 echo Private key file is missing. Please copy here the private key file (has extension .key)
if %cntb% GTR 1 echo More key files exist. Please check directory to ensure only one key file (.key extension) is present

goto done

:moveFiles

move %basename%*.pfx %~dp0\certs >nul
move *.key %~dp0\certs >nul
move *.cer %~dp0\certs >nul
echo Certificates moved to %~dp0\certs

:done
pause