#!/usr/bin/env bash
# ==========================================================================
#         ____            _                     _____           _
#        / ___| _   _ ___| |_ ___ _ __ ___     |_   _|__   ___ | |___
#        \___ \| | | / __| __/ _ \ '_ ` _ \ _____| |/ _ \ / _ \| / __|
#         ___) | |_| \__ \ ||  __/ | | | | |_____| | (_) | (_) | \__ \
#        |____/ \__, |___/\__\___|_| |_| |_|     |_|\___/ \___/|_|___/
#               |___/
#                             --- System-Tools ---
#                  https://www.nntb.no/~dreibh/system-tools/
# ==========================================================================
#
# PEM File Extractor
# Copyright (C) 2025 by Thomas Dreibholz
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
# Contact: thomas.dreibholz@gmail.com

# Bash options:
set -eu


# ###### Usage ##############################################################
usage () {
   echo >&2 "Usage: $0 [-o|--output-prefix file_name_prefix] [-f|--skip-first-entry] [-l|--skip-last-entry] [-q|--quiet] pem_file [...]"
   exit 1
}


# ###### Main program #######################################################

# ====== Handle arguments ===================================================
GETOPT="$(PATH=/usr/local/bin:${PATH} which getopt)"
options="$(${GETOPT} -o o:flqh --long output-prefix:,skip-first-entry,skip-last-entry,quiet,help -a -- "$@")"
# shellcheck disable=SC2181
if [[ $? -ne 0 ]]; then
   usage
fi

OUTPUT_PREFIX="output"
SKIP_FIRST=0
SKIP_LAST=0
QUIET=0
eval set -- "${options}"
while [ $# -gt 0 ] ; do
   case "$1" in
      -o | --output-prefix)
         OUTPUT_PREFIX="$2"
         shift 2
         ;;
      -f | --skip-first-entry)
         SKIP_FIRST=1
         shift
         ;;
      -l | --skip-last-entry)
         SKIP_LAST=1
         shift
         ;;
      -q | --quiet)
         QUIET=1
         shift
         ;;
      -h | --help)
         usage
         # shift
         ;;
      --)
         shift
         break
         ;;
  esac
done
if [ $# -lt 1 ] ; then
   usage
fi

# ====== Extract each PEM file ==============================================
certificate=0
csr=0
crl=0
key=0
lastOutputFile=""
while [ $# -gt 0 ] ; do
   PEM_FILE="$1"
   shift
   if [ ! -e "${PEM_FILE}" ] ; then
      echo >&2 "ERROR: Unable to find PEM file ${PEM_FILE}!"
      exit 1
   fi

   if [ ${QUIET} -eq 0 ] ; then
      echo -e "\e[34mExtracting ${PEM_FILE} ...\e[0m"
   fi
   outputFile=""
   entry=0
   while read -r line ; do
      if [ "${outputFile}" == "" ] ; then
         if [[ "${line}" =~ ^(-----BEGIN )(CERTIFICATE|CERTIFICATE REQUEST|X509 CRL|PRIVATE KEY|ENCRYPTED PRIVATE KEY)(-----)$ ]] ; then
            type="${BASH_REMATCH[2]}"
            if [ "${type}" == "CERTIFICATE" ] ; then
               certificate=$((certificate + 1))
               outputFile="${OUTPUT_PREFIX}${certificate}.crt"
            elif [ "${type}" == "CERTIFICATE REQUEST" ] ; then
               csr=$((csr + 1))
               outputFile="${OUTPUT_PREFIX}${csr}.csr"
            elif [ "${type}" == "X509 CRL" ] ; then
               crl=$((crl + 1))
               outputFile="${OUTPUT_PREFIX}${crl}.crl"
            elif [ "${type}" == "PRIVATE KEY" ] || \
                 [ "${type}" == "ENCRYPTED PRIVATE KEY" ] ; then
               key=$((crl + 1))
               outputFile="${OUTPUT_PREFIX}${key}.key"
               touch "${outputFile}"
               chmod 600 "${outputFile}"
            else
               echo >&2 "ERROR: Unexpected type ${type} in ${PEM_FILE}!"
               exit 1
            fi
            entry=$((entry + 1))
            echo "${line}" >>"${outputFile}.tmp"
         else
            echo >&2 "ERROR: Unexpected data in ${PEM_FILE}!"
         fi
      else
         if [[ "${line}" =~ ^(-----END ) ]] ; then
            echo "${line}" >>"${outputFile}.tmp"
            mv "${outputFile}.tmp" "${outputFile}"
            if [ ${SKIP_FIRST} -eq 1 ] && [ ${entry} -eq 1 ] ; then
               rm "${outputFile}"
            fi
            lastOutputFile="${outputFile}"
            outputFile=""
         else
            echo "${line}" >>"${outputFile}.tmp"
         fi
      fi
   done <"${PEM_FILE}"
done
if [ ${SKIP_LAST} -eq 1 ] && [ "${lastOutputFile}" != "" ] ; then
   rm "${lastOutputFile}"
fi
if [ ${QUIET} -eq 0 ] ; then
   echo -e "\e[34mDone: ${certificate} certificates, ${csr} CSRs, ${crl} CRLs, ${key} keys\e[0m"
fi
