#!/bin/bash

if [ -r '/etc/simple-pki/ca.conf' ]; then
  . '/etc/simple-pki/ca.conf'
fi

cd "${0%/*}"

remove_leading_spaces() {
  sed '
    s/^ \{'"$1"'\}//
    t
    d
  '
}

export CA_TYPE='Intermediate'

if [ -f '/etc/simple-pki/ca/root-ca.old.crt' ] \
&& [ "$(stat -c%Y '/etc/simple-pki/ca/root-ca.old.crt')" -ge "$(($(date +%s)-60*60*24*ca_min_duration))" ]; then
  export CA=signing-ca.old
else
  export CA=signing-ca
fi

tmp_dir=$(mktemp -d)
trap 'rm -rf --one-file-system "${tmp_dir}"' EXIT

while read -r csr; do
  csr_local="${tmp_dir}/${csr##*/}"
  host="${csr#*://}"
  host="${host%%/*}"
  curl -Ss \
    --resolve "${host}:443:${SSH_CLIENT%% *}" \
    --resolve "${host}:80:${SSH_CLIENT%% *}" \
    --connect-timeout 10 \
    --insecure "${csr}" -o "${csr_local}"
  if ! content=$(
    openssl req -text -noout -verify -in "${csr_local}" 2>/dev/null
  ); then
    >&2 printf 'verify of %s failed - skipping\n' "${csr_local##*/}"
    rm "${csr_local}"
    continue
  fi

  content=$(
    printf '%s\n' "${content}" \
    | sed -n '
      /^Certificate Request:$/,/^\S/p
    ' \
    | remove_leading_spaces 4 \
    | sed -n '
      /^Data:$/,/^\S/p
    ' \
    | remove_leading_spaces 4
  )
  cn=$(
    printf '%s\n' "${content}" \
    | sed '
      s/^Subject: //
      t
      d
    ' \
    | tr -d ' ' \
    | tr ',' '/' \
    | sed 's@^.*/CN=@@'
  )
  sans=$(
    printf '%s\n' "${content}" \
    | sed -n '
      /^Requested Extensions:$/,/^\S/ p
    ' \
    | remove_leading_spaces 4 \
    | sed -n '
      /^X\S\+ Subject Alternative Name:\s*$/,/^\S/ p
    ' \
    | remove_leading_spaces 4 \
    | sed '
      s/, /\n/g
    '
  )
  if printf '%s\n' "${sans}" | grep -vq '^\(DNS\|IP\):'; then
    >&2 echo 'invalid sans - skipping'
    rm "${csr_local}"
    continue
  fi
  sans=$(
    printf '%s\n' "${sans}" \
    | sed '
      s/^\(DNS\|IP\)://
    '
  )
  ok_sans=$(
    printf '%s\n' "${cn}" "${sans}" \
    | while read -r san; do
      resolved=false
      for address in $(
        dig +short "${san}" A \
        | grep -x '\([0-9]\+\.\)\{3\}[0-9]\+'
        dig +short "${san}" AAAA \
        | grep -x '[0-9a-f:]\+' \
        | sed 's/^.*$/[\0]/'
      ); do
        if curl -Ss \
          --resolve "${san}:80:${address}" \
          --resolve "${san}:443:${address}" \
          --connect-timeout 10 \
          --insecure \
          "${csr%%://*}"'://'"${san}/${csr#*//*/}" \
          | diff -q - "${csr_local}"; then
          resolved=true
          break
        fi
      done
      if ${resolved}; then
        printf '%s\n' "${san}"
      else
        >&2 printf 'invalid san "%s" - skipping\n' "${san}"
        rm "${csr_local}"
      fi
    done
  )
  if [ ! -f "${csr_local}" ]; then
    continue
  fi
  if [ "$(printf '%s\n' "${cn}" "${sans}")" != "${ok_sans}" ]; then
    >&2 echo 'some san was invalid - skipping'
    rm "${csr_local}"
    continue
  fi
  if ! openssl ca -batch -name signing_ca \
    -config '/etc/simple-pki/ca-ssl.conf' \
    -in "${csr_local}" \
    -out "${csr_local%.csr}.crt" \
    -extensions server_ext; then
    >&2 echo 'signing failed - skipping'
    rm -f "${csr_local}" "${csr_local%.csr}.crt"
    continue
  fi
  cat "${csr_local%.csr}.crt" '/etc/simple-pki/ca/signing-ca.crt' '/etc/simple-pki/ca/root-ca.crt' \
  > "${csr_local%.csr}.chain"
  rm "${csr_local}"
done

cd "${tmp_dir}"
tar -czf - *.crt *.chain
