]> git.street.me.uk Git - andy/dehydrated.git/blob - letsencrypt.sh
moved loading of configuration to seperate method
[andy/dehydrated.git] / letsencrypt.sh
1 #!/usr/bin/env bash
2 set -e
3 set -u
4 set -o pipefail
5 umask 077 # paranoid umask, we're creating private keys
6
7 # Get the directory in which this script is stored
8 SCRIPTDIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
9 BASEDIR="${SCRIPTDIR}"
10
11 # Setup default config values, search for and load configuration files
12 load_config() {
13   # Default values
14   CA="https://acme-v01.api.letsencrypt.org/directory"
15   LICENSE="https://letsencrypt.org/documents/LE-SA-v1.0.1-July-27-2015.pdf"
16   HOOK=
17   RENEW_DAYS="14"
18   PRIVATE_KEY="${BASEDIR}/private_key.pem"
19   KEYSIZE="4096"
20   WELLKNOWN="${BASEDIR}/.acme-challenges"
21   PRIVATE_KEY_RENEW="no"
22   OPENSSL_CNF="$(openssl version -d | cut -d'"' -f2)/openssl.cnf"
23   CONTACT_EMAIL=
24   LOCKFILE="${BASEDIR}/lock"
25
26   # Check for config in various locations
27   if [[ -z "${CONFIG:-}" ]]; then
28     for check_config in "/etc/letsencrypt.sh" "/usr/local/etc/letsencrypt.sh" "${PWD}" "${SCRIPTDIR}"; do
29       if [[ -e "${check_config}/config.sh" ]]; then
30         BASEDIR="${check_config}"
31         CONFIG="${check_config}/config.sh"
32         break
33       fi
34     done
35   fi
36
37   if [[ -z "${CONFIG:-}" ]]; then
38     echo "#" >&2
39     echo "# !! WARNING !! No config file found, using default config!" >&2
40     echo "#" >&2
41   elif [[ -e "${CONFIG}" ]]; then
42     echo "# INFO: Using config file ${CONFIG}"
43     BASEDIR="$(dirname "${CONFIG}")"
44     # shellcheck disable=SC1090
45     . "${CONFIG}"
46   else
47     echo "Specified config file doesn't exist." >&2
48     exit 1
49   fi
50
51   # Remove slash from end of BASEDIR. Mostly for cleaner outputs, doesn't change functionality.
52   BASEDIR="${BASEDIR%%/}"
53
54   # Check BASEDIR and set default variables
55   if [[ ! -d "${BASEDIR}" ]]; then
56    echo "BASEDIR does not exist: ${BASEDIR}" >&2
57    exit 1
58   fi
59 }
60
61 init_system() {
62   load_config
63
64   if [[ "${COMMAND}" = "env" ]]; then
65     return
66   fi
67
68   # Lockfile handling (prevents concurrent access)
69   set -o noclobber
70   if ! { date > "${LOCKFILE}"; } 2>/dev/null; then
71     echo "  + ERROR: Lock file '${LOCKFILE}' present, aborting." >&2
72     LOCKFILE="" # so remove_lock doesn't remove it
73     exit 1
74   fi
75   set +o noclobber
76
77   remove_lock() {
78     if [[ -n "${LOCKFILE}" ]]; then
79         rm -f "${LOCKFILE}"
80     fi
81   }
82   trap 'remove_lock' EXIT
83
84   # Export some environment variables to be used in hook script
85   export WELLKNOWN
86   export BASEDIR
87   export CONFIG
88
89   # Get CA URLs
90   CA_DIRECTORY="$(http_request get "${CA}")"
91   CA_NEW_CERT="$(printf "%s" "${CA_DIRECTORY}" | get_json_string_value new-cert)" &&
92   CA_NEW_AUTHZ="$(printf "%s" "${CA_DIRECTORY}" | get_json_string_value new-authz)" &&
93   CA_NEW_REG="$(printf "%s" "${CA_DIRECTORY}" | get_json_string_value new-reg)" &&
94   # shellcheck disable=SC2015
95   CA_REVOKE_CERT="$(printf "%s" "${CA_DIRECTORY}" | get_json_string_value revoke-cert)" ||
96   (echo "Error retrieving ACME/CA-URLs, check if your configured CA points to the directory entrypoint." >&2; exit 1)
97
98
99   # check private key ...
100   register="0"
101   if [[ -n "${PARAM_PRIVATE_KEY:-}" ]]; then
102     # a private key was specified from the command line so use it for this run
103     echo "Using private key ${PARAM_PRIVATE_KEY} instead of account key"
104     PRIVATE_KEY="${PARAM_PRIVATE_KEY}"
105     if ! openssl rsa -in "${PRIVATE_KEY}" -check 2>/dev/null > /dev/null; then
106       echo " + ERROR: private key is not valid, can not continue" >&2
107       exit 1
108     fi
109   else
110     # Check if private account key exists, if it doesn't exist yet generate a new one (rsa key)
111     if [[ ! -e "${PRIVATE_KEY}" ]]; then
112       echo "+ Generating account key..."
113       _openssl genrsa -out "${PRIVATE_KEY}" "${KEYSIZE}"
114       register="1"
115     fi
116   fi
117
118   # Get public components from private key and calculate thumbprint
119   pubExponent64="$(openssl rsa -in "${PRIVATE_KEY}" -noout -text | grep publicExponent | grep -oE "0x[a-f0-9]+" | cut -d'x' -f2 | hex2bin | urlbase64)"
120   pubMod64="$(openssl rsa -in "${PRIVATE_KEY}" -noout -modulus | cut -d'=' -f2 | hex2bin | urlbase64)"
121
122   thumbprint="$(printf '{"e":"%s","kty":"RSA","n":"%s"}' "${pubExponent64}" "${pubMod64}" | openssl sha -sha256 -binary | urlbase64)"
123
124   # If we generated a new private key in the step above we have to register it with the acme-server
125   if [[ "${register}" = "1" ]]; then
126     echo "+ Registering account key with letsencrypt..."
127     if [ -z "${CA_NEW_REG}" ]; then
128       echo " + ERROR: Certificate authority doesn't allow registrations." >&2
129       exit 1
130     fi
131     # if an email for the contact has been provided then adding it to the registration request
132     if [[ -n "${CONTACT_EMAIL}" ]]; then
133       signed_request "${CA_NEW_REG}" '{"resource": "new-reg", "contact":["mailto:'"${CONTACT_EMAIL}"'"], "agreement": "'"$LICENSE"'"}' > /dev/null
134     else
135       signed_request "${CA_NEW_REG}" '{"resource": "new-reg", "agreement": "'"$LICENSE"'"}' > /dev/null
136     fi
137   fi
138
139   if [[ -e "${BASEDIR}/domains.txt" ]]; then
140     DOMAINS_TXT="${BASEDIR}/domains.txt"
141   else
142     echo " + ERROR: domains.txt not found" >&2
143     exit 1
144   fi
145
146   if [[ ! -e "${WELLKNOWN}" ]]; then
147     echo " + ERROR: WELLKNOWN directory doesn't exist, please create ${WELLKNOWN} and set appropriate permissions." >&2
148     exit 1
149   fi
150 }
151
152 anti_newline() {
153   tr -d '\n\r'
154 }
155
156 urlbase64() {
157   # urlbase64: base64 encoded string with '+' replaced with '-' and '/' replaced with '_'
158   openssl base64 -e | anti_newline | sed 's/=*$//g' | tr '+/' '-_'
159 }
160
161 hex2bin() {
162   # Store hex string from stdin
163   tmphex="$(cat)"
164
165   # Remove spaces
166   hex=''
167   for ((i=0; i<${#tmphex}; i+=1)); do
168     test "${tmphex:$i:1}" == " " || hex="${hex}${tmphex:$i:1}"
169   done
170
171   # Add leading zero
172   test $((${#hex} & 1)) == 0 || hex="0${hex}"
173
174   # Convert to escaped string
175   escapedhex=''
176   for ((i=0; i<${#hex}; i+=2)); do
177     escapedhex=$escapedhex\\x${hex:$i:2}
178   done
179
180   # Convert to binary data
181   printf -- "${escapedhex}"
182 }
183
184 get_json_string_value() {
185   grep -Eo '"'"${1}"'":[[:space:]]*"[^"]*"' | cut -d'"' -f4
186 }
187
188 get_json_array() {
189   grep -Eo '"'"${1}"'":[^\[]*\[[^]]*]'
190 }
191
192 http_request() {
193   tempcont="$(mktemp)"
194
195   if [[ "${1}" = "head" ]]; then
196     statuscode="$(curl -s -w "%{http_code}" -o "${tempcont}" "${2}" -I)"
197   elif [[ "${1}" = "get" ]]; then
198     statuscode="$(curl -s -w "%{http_code}" -o "${tempcont}" "${2}")"
199   elif [[ "${1}" = "post" ]]; then
200     statuscode="$(curl -s -w "%{http_code}" -o "${tempcont}" "${2}" -d "${3}")"
201   fi
202
203   if [[ ! "${statuscode:0:1}" = "2" ]]; then
204     echo "  + ERROR: An error occurred while sending ${1}-request to ${2} (Status ${statuscode})" >&2
205     echo >&2
206     echo "Details:" >&2
207     cat "${tempcont}" >&2
208     rm -f "${tempcont}"
209
210     # Wait for hook script to clean the challenge if used
211     if [[ -n "${HOOK}" ]] && [[ -n "${challenge_token:+set}"  ]]; then
212       ${HOOK} "clean_challenge" '' "${challenge_token}" "${keyauth}"
213     fi
214
215     # remove temporary domains.txt file if used
216     if [[ -n "${PARAM_DOMAIN:-}" ]]; then
217       rm "${DOMAINS_TXT}"
218     fi
219
220     exit 1
221   fi
222
223   cat "${tempcont}"
224   rm -f "${tempcont}"
225 }
226
227 # OpenSSL writes to stderr/stdout even when there are no errors. So just
228 # display the output if the exit code was != 0 to simplify debugging.
229 _openssl() {
230   set +e
231   out="$(openssl "${@}" 2>&1)"
232   res=$?
233   set -e
234   if [[ $res -ne 0 ]]; then
235     echo "  + ERROR: failed to run $* (Exitcode: $res)" >&2
236     echo >&2
237     echo "Details:" >&2
238     echo "$out" >&2
239     exit $res
240   fi
241 }
242
243 signed_request() {
244   # Encode payload as urlbase64
245   payload64="$(printf '%s' "${2}" | urlbase64)"
246
247   # Retrieve nonce from acme-server
248   nonce="$(http_request head "${CA}" | grep Replay-Nonce: | awk -F ': ' '{print $2}' | anti_newline)"
249
250   # Build header with just our public key and algorithm information
251   header='{"alg": "RS256", "jwk": {"e": "'"${pubExponent64}"'", "kty": "RSA", "n": "'"${pubMod64}"'"}}'
252
253   # Build another header which also contains the previously received nonce and encode it as urlbase64
254   protected='{"alg": "RS256", "jwk": {"e": "'"${pubExponent64}"'", "kty": "RSA", "n": "'"${pubMod64}"'"}, "nonce": "'"${nonce}"'"}'
255   protected64="$(printf '%s' "${protected}" | urlbase64)"
256
257   # Sign header with nonce and our payload with our private key and encode signature as urlbase64
258   signed64="$(printf '%s' "${protected64}.${payload64}" | openssl dgst -sha256 -sign "${PRIVATE_KEY}" | urlbase64)"
259
260   # Send header + extended header + payload + signature to the acme-server
261   data='{"header": '"${header}"', "protected": "'"${protected64}"'", "payload": "'"${payload64}"'", "signature": "'"${signed64}"'"}'
262
263   http_request post "${1}" "${data}"
264 }
265
266 sign_domain() {
267   domain="${1}"
268   altnames="${*}"
269
270   echo " + Signing domains..."
271   if [[ -z "${CA_NEW_AUTHZ}" ]] || [[ -z "${CA_NEW_CERT}" ]]; then
272     echo " + ERROR: Certificate authority doesn't allow certificate signing" >&2
273     exit 1
274   fi
275   timestamp="$(date +%s)"
276
277   # If there is no existing certificate directory => make it
278   if [[ ! -e "${BASEDIR}/certs/${domain}" ]]; then
279     echo " + make directory ${BASEDIR}/certs/${domain} ..."
280     mkdir -p "${BASEDIR}/certs/${domain}"
281   fi
282
283   privkey="privkey.pem"
284   # generate a new private key if we need or want one
285   if [[ ! -f "${BASEDIR}/certs/${domain}/privkey.pem" ]] || [[ "${PRIVATE_KEY_RENEW}" = "yes" ]]; then
286     echo " + Generating private key..."
287     privkey="privkey-${timestamp}.pem"
288     _openssl genrsa -out "${BASEDIR}/certs/${domain}/privkey-${timestamp}.pem" "${KEYSIZE}"
289   fi
290
291   # Generate signing request config and the actual signing request
292   SAN=""
293   for altname in $altnames; do
294     SAN+="DNS:${altname}, "
295   done
296   SAN="${SAN%%, }"
297   echo " + Generating signing request..."
298   local tmp_openssl_cnf
299   tmp_openssl_cnf="$(mktemp)"
300   cat "${OPENSSL_CNF}" > "${tmp_openssl_cnf}"
301   printf "[SAN]\nsubjectAltName=%s" "${SAN}" >> "${tmp_openssl_cnf}"
302   openssl req -new -sha256 -key "${BASEDIR}/certs/${domain}/${privkey}" -out "${BASEDIR}/certs/${domain}/cert-${timestamp}.csr" -subj "/CN=${domain}/" -reqexts SAN -config "${tmp_openssl_cnf}"
303   rm -f "${tmp_openssl_cnf}"
304
305   # Request and respond to challenges
306   for altname in $altnames; do
307     # Ask the acme-server for new challenge token and extract them from the resulting json block
308     echo " + Requesting challenge for ${altname}..."
309     response="$(signed_request "${CA_NEW_AUTHZ}" '{"resource": "new-authz", "identifier": {"type": "dns", "value": "'"${altname}"'"}}')"
310
311     challenges="$(printf '%s\n' "${response}" | get_json_array challenges)"
312     repl=$'\n''{' # fix syntax highlighting in Vim
313     challenge="$(printf "%s" "${challenges//\{/${repl}}" | grep 'http-01')"
314     challenge_token="$(printf '%s' "${challenge}" | get_json_string_value token | sed 's/[^A-Za-z0-9_\-]/_/g')"
315     challenge_uri="$(printf '%s' "${challenge}" | get_json_string_value uri)"
316
317     if [[ -z "${challenge_token}" ]] || [[ -z "${challenge_uri}" ]]; then
318       echo "  + Error: Can't retrieve challenges (${response})" >&2
319       exit 1
320     fi
321
322     # Challenge response consists of the challenge token and the thumbprint of our public certificate
323     keyauth="${challenge_token}.${thumbprint}"
324
325     # Store challenge response in well-known location and make world-readable (so that a webserver can access it)
326     printf '%s' "${keyauth}" > "${WELLKNOWN}/${challenge_token}"
327     chmod a+r "${WELLKNOWN}/${challenge_token}"
328
329     # Wait for hook script to deploy the challenge if used
330     if [[ -n "${HOOK}" ]]; then
331         ${HOOK} "deploy_challenge" "${altname}" "${challenge_token}" "${keyauth}"
332     fi
333
334     # Ask the acme-server to verify our challenge and wait until it becomes valid
335     echo " + Responding to challenge for ${altname}..."
336     result="$(signed_request "${challenge_uri}" '{"resource": "challenge", "keyAuthorization": "'"${keyauth}"'"}')"
337
338     status="$(printf '%s\n' "${result}" | get_json_string_value status)"
339
340     # get status until a result is reached => not pending anymore
341     while [[ "${status}" = "pending" ]]; do
342       sleep 1
343       status="$(http_request get "${challenge_uri}" | get_json_string_value status)"
344     done
345
346     rm -f "${WELLKNOWN}/${challenge_token}"
347
348     # Wait for hook script to clean the challenge if used
349     if [[ -n "${HOOK}" ]] && [[ -n "${challenge_token}" ]]; then
350       ${HOOK} "clean_challenge" "${altname}" "${challenge_token}" "${keyauth}"
351     fi
352
353     if [[ "${status}" = "valid" ]]; then
354       echo " + Challenge is valid!"
355     else
356       echo " + Challenge is invalid! (returned: ${status})" >&2
357       exit 1
358     fi
359
360   done
361
362   # Finally request certificate from the acme-server and store it in cert-${timestamp}.pem and link from cert.pem
363   echo " + Requesting certificate..."
364   csr64="$(openssl req -in "${BASEDIR}/certs/${domain}/cert-${timestamp}.csr" -outform DER | urlbase64)"
365   crt64="$(signed_request "${CA_NEW_CERT}" '{"resource": "new-cert", "csr": "'"${csr64}"'"}' | openssl base64 -e)"
366   crt_path="${BASEDIR}/certs/${domain}/cert-${timestamp}.pem"
367   printf -- '-----BEGIN CERTIFICATE-----\n%s\n-----END CERTIFICATE-----\n' "${crt64}" > "${crt_path}"
368   # try to load the certificate to detect corruption
369   echo " + Checking certificate..."
370   _openssl x509 -text < "${crt_path}"
371
372   # Create fullchain.pem
373   echo " + Creating fullchain.pem..."
374   cat "${crt_path}" > "${BASEDIR}/certs/${domain}/fullchain-${timestamp}.pem"
375   http_request get "$(openssl x509 -in "${BASEDIR}/certs/${domain}/cert-${timestamp}.pem" -noout -text | grep 'CA Issuers - URI:' | cut -d':' -f2-)" > "${BASEDIR}/certs/${domain}/chain-${timestamp}.pem"
376   if ! grep "BEGIN CERTIFICATE" "${BASEDIR}/certs/${domain}/chain-${timestamp}.pem" > /dev/null 2>&1; then
377     openssl x509 -in "${BASEDIR}/certs/${domain}/chain-${timestamp}.pem" -inform DER -out "${BASEDIR}/certs/${domain}/chain-${timestamp}.pem" -outform PEM
378   fi
379   ln -sf "chain-${timestamp}.pem" "${BASEDIR}/certs/${domain}/chain.pem"
380   cat "${BASEDIR}/certs/${domain}/chain-${timestamp}.pem" >> "${BASEDIR}/certs/${domain}/fullchain-${timestamp}.pem"
381   ln -sf "fullchain-${timestamp}.pem" "${BASEDIR}/certs/${domain}/fullchain.pem"
382
383   # Update remaining symlinks
384   if [ ! "${privkey}" = "privkey.pem" ]; then
385     ln -sf "privkey-${timestamp}.pem" "${BASEDIR}/certs/${domain}/privkey.pem"
386   fi
387
388   ln -sf "cert-${timestamp}.csr" "${BASEDIR}/certs/${domain}/cert.csr"
389   ln -sf "cert-${timestamp}.pem" "${BASEDIR}/certs/${domain}/cert.pem"
390
391   # Wait for hook script to clean the challenge and to deploy cert if used
392   if [[ -n "${HOOK}" ]]; then
393       ${HOOK} "deploy_cert" "${domain}" "${BASEDIR}/certs/${domain}/privkey.pem" "${BASEDIR}/certs/${domain}/cert.pem" "${BASEDIR}/certs/${domain}/fullchain.pem"
394   fi
395
396   unset challenge_token
397   echo " + Done!"
398 }
399
400
401 # Usage: --cron (-c)
402 # Description: Sign/renew non-existant/changed/expiring certificates.
403 command_sign_domains() {
404   if [[ -n "${PARAM_DOMAIN:-}" ]]; then
405     # we are using a temporary domains.txt file so we don't need to duplicate any code
406     DOMAINS_TXT="$(mktemp)"
407     echo "${PARAM_DOMAIN}" > "${DOMAINS_TXT}"
408   fi
409   # Generate certificates for all domains found in domains.txt. Check if existing certificate are about to expire
410   <"${DOMAINS_TXT}" sed 's/^[[:space:]]*//g;s/[[:space:]]*$//g' | grep -vE '^(#|$)' | while read -r line; do
411     domain="$(printf '%s\n' "${line}" | cut -d' ' -f1)"
412     morenames="$(printf '%s\n' "${line}" | cut -s -d' ' -f2-)"
413     cert="${BASEDIR}/certs/${domain}/cert.pem"
414
415     force_renew="${PARAM_FORCE:-no}"
416
417     if [[ -z "${morenames}" ]];then
418       echo "Processing ${domain}"
419     else
420       echo "Processing ${domain} with SAN: ${morenames}"
421     fi
422
423     if [[ -e "${cert}" ]]; then
424       echo -n " + Checking domain name(s) of existing cert..."
425
426       certnames="$(openssl x509 -in "${cert}" -text -noout | grep DNS: | sed 's/DNS://g' | tr -d ' ' | tr ',' '\n' | sort -u | tr '\n' ' ' | sed 's/ $//')"
427       givennames="$(echo "${domain}" "${morenames}"| tr ' ' '\n' | sort -u | tr '\n' ' ' | sed 's/ $//' | sed 's/^ //')"
428
429       if [[ "${certnames}" = "${givennames}" ]]; then
430         echo " unchanged."
431       else
432         echo " changed!"
433         echo " + Domain name(s) are not matching!"
434         echo " + Names in old certificate: ${certnames}"
435         echo " + Configured names: ${givennames}"
436         echo " + Forcing renew."
437         force_renew="yes"
438       fi
439     fi
440
441     if [[ -e "${cert}" ]]; then
442       echo " + Checking expire date of existing cert..."
443
444       valid="$(openssl x509 -enddate -noout -in "${cert}" | cut -d= -f2- )"
445
446       echo -n " + Valid till ${valid} "
447       if openssl x509 -checkend $((RENEW_DAYS * 86400)) -noout -in "${cert}"; then
448         echo -n "(Longer than ${RENEW_DAYS} days). "
449         if [[ "${force_renew}" = "yes" ]]; then
450           echo "Ignoring because renew was forced!"
451         else
452           echo "Skipping!"
453           continue
454         fi
455       else
456         echo "(Less than ${RENEW_DAYS} days). Renewing!"
457       fi
458     fi
459
460     # shellcheck disable=SC2086
461     sign_domain $line
462   done || true
463
464   # remove temporary domains.txt file if used
465   if [[ -n "${PARAM_DOMAIN:-}" ]]; then
466     rm -f "${DOMAINS_TXT}"
467   fi
468 }
469
470 # Usage: --revoke (-r) path/to/cert.pem
471 # Description: Revoke specified certificate
472 command_revoke() {
473   cert="${1}"
474   if [[ -L "${cert}" ]]; then
475     # follow symlink and use real certificate name (so we move the real file and not the symlink at the end)
476     local link_target
477     link_target="$(readlink -n "${cert}")"
478     if [[ "${link_target}" =~ ^/ ]]; then
479       cert="${link_target}"
480     else
481       cert="$(dirname "${cert}")/${link_target}"
482     fi
483   fi
484   if [[ ! -f "${cert}" ]]; then
485     echo "ERROR: Could not find certificate ${cert}"
486     exit 1
487   fi
488   echo "Revoking ${cert}"
489   if [[ -z "${CA_REVOKE_CERT}" ]]; then
490     echo " + ERROR: Certificate authority doesn't allow certificate revocation." >&2
491     exit 1
492   fi
493   cert64="$(openssl x509 -in "${cert}" -inform PEM -outform DER | urlbase64)"
494   response="$(signed_request "${CA_REVOKE_CERT}" '{"resource": "revoke-cert", "certificate": "'"${cert64}"'"}')"
495   # if there is a problem with our revoke request http_request (via signed_request) will report this and "exit 1" out
496   # so if we are here, it is safe to assume the request was successful
497   echo " + SUCCESS"
498   echo " + renaming certificate to ${cert}-revoked"
499   mv -f "${cert}" "${cert}-revoked"
500 }
501
502 # Usage: --help (-h)
503 # Description: Show help text
504 command_help() {
505   echo "Usage: ${0} [-h] [command [argument]] [parameter [argument]] [parameter [argument]] ..."
506   echo
507   echo "Default command: help"
508   echo
509   (
510   echo "Commands:"
511   grep -e '^[[:space:]]*# Usage:' -e '^[[:space:]]*# Description:' -e '^command_.*()[[:space:]]*{' "${0}" | while read -r usage; read -r description; read -r command; do
512     if [[ ! "${usage}" =~ Usage ]] || [[ ! "${description}" =~ Description ]] || [[ ! "${command}" =~ ^command_ ]]; then
513       echo "Error generating help text." >&2
514       exit 1
515     fi
516     printf " %s\t%s\n" "${usage##"# Usage: "}" "${description##"# Description: "}"
517   done
518   echo "---"
519   echo "Parameters:"
520   grep -E -e '^[[:space:]]*# PARAM_Usage:' -e '^[[:space:]]*# PARAM_Description:' "${0}" | while read -r usage; read -r description; do
521     if [[ ! "${usage}" =~ Usage ]] || [[ ! "${description}" =~ Description ]]; then
522       echo "Error generating help text." >&2
523       exit 1
524     fi
525     printf " %s\t%s\n" "${usage##"# PARAM_Usage: "}" "${description##"# PARAM_Description: "}"
526   done
527   ) | column -t -s $'\t' | sed 's/^---$//g'
528 }
529
530 # Usage: --env (-e)
531 # Description: Output configuration variables for use in other scripts
532 command_env() {
533   echo "# letsencrypt.sh configuration"
534   typeset -p CA LICENSE BASEDIR WELLKNOWN PRIVATE_KEY KEYSIZE OPENSSL_CNF HOOK RENEW_DAYS PRIVATE_KEY_RENEW CONTACT_EMAIL
535   exit 0
536 }
537
538 args=""
539 # change long args to short args
540 # inspired by http://kirk.webfinish.com/?p=45
541 for arg; do
542   case "${arg}" in
543     --help)    args="${args}-h ";;
544     --cron)    args="${args}-c ";;
545     --domain)  args="${args}-d ";;
546     --force )  args="${args}-x ";;
547     --revoke)  args="${args}-r ";;
548     --privkey) args="${args}-p ";;
549     --config)  args="${args}-f ";;
550     --env)     args="${args}-e ";;
551     --*)
552       echo "Unknown parameter detected: ${arg}" >&2
553       echo >&2
554       command_help >&2
555       exit 1
556       ;;
557     # pass through anything else
558     *) args="${args}\"${arg}\" ";;
559     esac
560 done
561
562 # Reset the positional parameters to the short options
563 eval set -- "${args}"
564
565 COMMAND=""
566 set_command() {
567   if [[ ! -z "${COMMAND}" ]]; then
568     echo "Only one command can be executed at a time." >&2
569     echo "See help (-h) for more information." >&2
570     exit 1
571   fi
572   COMMAND="${1}"
573 }
574
575 check_parameters() {
576   if [[ -z "${@}" ]]; then
577     echo "The specified command requires additional parameters. See help:" >&2
578     echo >&2
579     command_help >&2
580     exit 1
581   fi
582 }
583
584 while getopts ":hcer:d:xf:p:" option; do
585   case "${option}" in
586     h)
587       command_help
588       exit 0
589       ;;
590     c)
591       set_command sign_domains
592       ;;
593     e)
594       set_command env
595       ;;
596     r)
597       set_command revoke
598       check_parameters "${OPTARG:-}"
599       revoke_me="${OPTARG}"
600       ;;
601     d)
602       # PARAM_Usage: --domain (-d) domain.tld
603       # PARAM_Description: Use specified domain name instead of domains.txt, use multiple times for certificate with SAN names
604       check_parameters "${OPTARG:-}"
605       if [[ -z "${PARAM_DOMAIN:-}" ]]; then
606         PARAM_DOMAIN="${OPTARG}"
607       else
608         PARAM_DOMAIN="${PARAM_DOMAIN} ${OPTARG}"
609        fi
610       ;;
611     x)
612       # PARAM_Usage: --force (-x)
613       # PARAM_Description: force renew of certificate even if it is longer valid than value in RENEW_DAYS
614       PARAM_FORCE="yes"
615       ;;
616     f)
617       # PARAM_Usage: --config (-f) path/to/config.sh
618       # PARAM_Description: Use specified config file
619       check_parameters "${OPTARG:-}"
620       CONFIG="${OPTARG}"
621       ;;
622     p)
623       # PARAM_Usage: --privkey (-p) path/to/key.pem
624       # PARAM_Description: Use specified private key instead of account key (useful for revocation)
625       check_parameters "${OPTARG:-}"
626       PARAM_PRIVATE_KEY="${OPTARG}"
627       ;;
628     *)
629       echo "Unknown parameter detected: -${OPTARG}" >&2
630       echo >&2
631       command_help >&2
632       exit 1
633       ;;
634   esac
635 done
636
637 if [[ -z "${COMMAND}" ]]; then
638   command_help
639   exit 1
640 fi
641
642 init_system
643
644 case "${COMMAND}" in
645   sign_domains)
646     command_sign_domains
647     ;;
648   env)
649     command_env
650     ;;
651   revoke)
652     command_revoke "${revoke_me}"
653     ;;
654 esac