7 umask 077 # paranoid umask, we're creating private keys
9 SCRIPTDIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
10 BASEDIR="${SCRIPTDIR}"
11 LETSENCRYPT="/etc/letsencrypt"
13 eval "$("${SCRIPTDIR}/letsencrypt.sh" --env)"
15 if [[ ! -e "${LETSENCRYPT}" ]]; then
16 echo "No existing letsencrypt files found."
20 if [[ -e "${BASEDIR}/domains.txt" ]]; then
21 DOMAINS_TXT="${BASEDIR}/domains.txt"
22 elif [[ -e "${SCRIPTDIR}/domains.txt" ]]; then
23 DOMAINS_TXT="${SCRIPTDIR}/domains.txt"
25 echo "You have to create a domains.txt file listing the domains you want certificates for. Have a look at domains.txt.example."
26 echo "For the purpose of this import script the file can be empty, but it has to exist."
30 for certdir in "${LETSENCRYPT}/live/"*; do
31 domain="$(basename "${certdir}")"
32 echo "Processing ${domain}"
34 # Check if we already have a certificate for the same (main) domain
35 if [ -e "${BASEDIR}/certs/${domain}" ]; then
36 echo " + Skipping: Found existing certificate directory, don't want to delete anything."
40 # Check if private-key, certificate and fullchain exist
41 if [[ ! -e "${certdir}/privkey.pem" ]]; then
42 echo " + Skipping: Private key is missing."
45 if [[ ! -e "${certdir}/cert.pem" ]]; then
46 echo " + Skipping: Certificate is missing."
49 if [[ ! -e "${certdir}/fullchain.pem" ]]; then
50 echo " + Skipping: Chain is missing."
54 # Check if certificate still valid
55 if ! openssl x509 -checkend 0 -noout -in "${certdir}/cert.pem" >/dev/null 2>&1; then
56 echo " + Skipping: Certificate is expired."
61 timestamp="$(date +%s)"
63 echo " + Adding list of domains to ${DOMAINS_TXT}"
64 SAN="$(openssl x509 -in "${certdir}/cert.pem" -noout -text | grep -A1 "Subject Alternative Name" | grep "DNS")"
68 for altname in ${SAN}; do
69 if [[ ! "${altname}" = "${domain}" ]]; then
70 altnames="${altnames} ${altname}"
73 echo "${altnames}" >> "${DOMAINS_TXT}"
75 mkdir -p "${BASEDIR}/certs/${domain}"
77 echo " + Importing private key"
78 cat "${certdir}/privkey.pem" > "${BASEDIR}/certs/${domain}/privkey-${timestamp}.pem"
79 ln -s "privkey-${timestamp}.pem" "${BASEDIR}/certs/${domain}/privkey.pem"
81 echo " + Importing certificate"
82 cat "${certdir}/cert.pem" > "${BASEDIR}/certs/${domain}/cert-${timestamp}.pem"
83 ln -s "cert-${timestamp}.pem" "${BASEDIR}/certs/${domain}/cert.pem"
85 echo " + Importing chain"
86 cat "${certdir}/fullchain.pem" > "${BASEDIR}/certs/${domain}/fullchain-${timestamp}.pem"
87 ln -s "fullchain-${timestamp}.pem" "${BASEDIR}/certs/${domain}/fullchain.pem"