yum install -y -q -e 0 unzip;

if [[ ! -d /certs/$1-certs ]]; then
  mkdir /certs/$1-certs
fi;

for folder in /certs/$1-certs/*/ ; do
    rm -Rf $folder
done

if [[ ! -f /certs/$1-certs/bundle.zip ]]; then
  bin/elasticsearch-certutil \
    cert \
    --silent \
    --days 1095 \
    --pem \
    --in config/certificates/$1-instances.yml \
    -out /certs/$1-certs/bundle.zip;
  unzip /certs/$1-certs/bundle.zip -d /certs/$1-certs;
  rm /certs/$1-certs/bundle.zip;
fi;

for file in /certs/$1-certs/*/*.key ; do
    openssl pkcs8 -in $file \
      -topk8  -nocrypt -out ${file/.key/.pkcs8.key};
done

chown -R 1000:0 /certs/$1-certs
