#!/usr/bin/env bash
set -Eeuo pipefail

CONFIG="${LEGO_CONFIG_FILE:-/etc/lego/.lego.yml}"

[[ -r "${CONFIG}" ]] || {
    printf 'ERROR: lego configuration is not readable: %s\n' "${CONFIG}" >&2
    exit 1
}

# Restrict parsing to the top-level accounts section. lego-init writes account
# properties with four spaces of indentation.
awk '
    /^[[:space:]]*accounts:[[:space:]]*$/ {
        in_accounts = 1
        next
    }

    in_accounts && /^[^[:space:]]/ {
        exit
    }

    in_accounts && /^    email:[[:space:]]*/ {
        value = $0
        sub(/^    email:[[:space:]]*/, "", value)
        sub(/[[:space:]]+#.*$/, "", value)
        gsub(/^[[:space:]]+|[[:space:]]+$/, "", value)

        if ((value ~ /^\047.*\047$/) || (value ~ /^\".*\"$/)) {
            value = substr(value, 2, length(value) - 2)
        }

        gsub(/\047\047/, "\047", value)
        print value
        exit
    }
' "${CONFIG}"
