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

CONFIG_DIR="${LEGO_CONFIG_DIR:-/etc/lego}"
LEGO_GROUP="${LEGO_GROUP:-lego}"

command -v getent >/dev/null 2>&1 || {
    printf 'ERROR: getent is required to verify the lego group\n' >&2
    exit 1
}

getent group "${LEGO_GROUP}" >/dev/null 2>&1 || {
    printf 'ERROR: required group does not exist: %s\n' "${LEGO_GROUP}" >&2
    exit 1
}

install -d -o root -g "${LEGO_GROUP}" -m 2750 "${CONFIG_DIR}"
install -d -o root -g "${LEGO_GROUP}" -m 2750 \
    "${CONFIG_DIR}/pre" \
    "${CONFIG_DIR}/post" \
    "${CONFIG_DIR}/hooks"
install -d -o root -g "${LEGO_GROUP}" -m 2770 \
    "${CONFIG_DIR}/accounts" \
    "${CONFIG_DIR}/certificates"

# Keep all lego state owned by root:lego. Do not follow symlinks while changing
# their ownership; packaged hook symlinks may point outside /etc/lego.
find -P "${CONFIG_DIR}" -xdev -exec chown -h root:"${LEGO_GROUP}" {} +

# Configuration and account/certificate material may contain private keys.
find -P "${CONFIG_DIR}/accounts" "${CONFIG_DIR}/certificates" \
    -xdev -type d -exec chmod 2770 {} +
find -P "${CONFIG_DIR}/accounts" "${CONFIG_DIR}/certificates" \
    -xdev -type f -exec chmod 0660 {} +

# Hook directories inherit the lego group, while hook files remain executable
# only by root and members of the lego group.
find -P "${CONFIG_DIR}/pre" "${CONFIG_DIR}/post" "${CONFIG_DIR}/hooks" \
    -xdev -type d -exec chmod 2750 {} +
find -P "${CONFIG_DIR}/pre" "${CONFIG_DIR}/post" "${CONFIG_DIR}/hooks" \
    -xdev -type f -exec chmod 0750 {} +

# Protect top-level configuration files without making hook symlinks writable.
find -P "${CONFIG_DIR}" -xdev -mindepth 1 -maxdepth 1 -type f -exec chmod 0640 {} +
chmod 2750 "${CONFIG_DIR}"
