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

LICENSE_FILE="${TEXISE_LICENSE_KEYS_FILE:-/etc/texise/license-keys}"

usage() {
  cat <<'USAGE'
Usage:
  texise-license add <license-key>
  texise-license remove <license-key>
  texise-license list

Predefined keys are stored as SHA-256 hashes. The original key is never written
into /etc/texise/license-keys.
USAGE
}

die() {
  printf 'texise-license: %s\n' "$*" >&2
  exit 1
}

require_root_for_write() {
  [[ "${EUID}" -eq 0 ]] || die 'add/remove require root privileges.'
}

hash_key() {
  local key="$1"
  [[ -n "${key}" ]] || die 'license key cannot be empty.'
  printf '%s' "${key}" | tr '[:lower:]' '[:upper:]' | openssl dgst -sha256 -r | awk '{print $1}'
}

hash_key_legacy() {
  local key="$1"
  printf '%s' "${key}" | openssl dgst -sha256 -r | awk '{print $1}'
}

fingerprint() {
  local hash="$1"
  printf '%s:%s:%s\n' "${hash:0:4}" "${hash:4:4}" "${hash:8:4}"
}

command_name="${1:-}"
case "${command_name}" in
  add)
    require_root_for_write
    [[ $# -eq 2 ]] || { usage; exit 2; }
    hash="$(hash_key "$2")"
    entry="sha256:${hash}"
    install -d -o root -g texise -m 0750 "$(dirname "${LICENSE_FILE}")"
    touch "${LICENSE_FILE}"
    chown root:texise "${LICENSE_FILE}"
    chmod 0640 "${LICENSE_FILE}"
    if grep -Fqx "${entry}" "${LICENSE_FILE}"; then
      printf 'License already exists. Fingerprint: '
      fingerprint "${hash}"
      exit 0
    fi
    printf '%s\n' "${entry}" >> "${LICENSE_FILE}"
    printf 'Added TeXise Pro licence. Fingerprint: '
    fingerprint "${hash}"
    ;;
  remove)
    require_root_for_write
    [[ $# -eq 2 ]] || { usage; exit 2; }
    [[ -f "${LICENSE_FILE}" ]] || die "license file not found: ${LICENSE_FILE}"
    hash="$(hash_key "$2")"
    legacy_hash="$(hash_key_legacy "$2")"
    entry="sha256:${hash}"
    legacy_entry="sha256:${legacy_hash}"
    tmp="$(mktemp "${LICENSE_FILE}.XXXXXX")"
    trap 'rm -f "${tmp:-}"' EXIT
    awk -v current="${entry}" -v legacy="${legacy_entry}" '$0 != current && $0 != legacy' "${LICENSE_FILE}" > "${tmp}"
    chown root:texise "${tmp}"
    chmod 0640 "${tmp}"
    mv "${tmp}" "${LICENSE_FILE}"
    trap - EXIT
    printf 'Removed matching licence if present. Fingerprint: '
    fingerprint "${hash}"
    ;;
  list)
    [[ $# -eq 1 ]] || { usage; exit 2; }
    [[ -f "${LICENSE_FILE}" ]] || exit 0
    while IFS= read -r line; do
      case "${line}" in
        sha256:*) fingerprint "${line#sha256:}" ;;
        ''|'#'*) ;;
      esac
    done < "${LICENSE_FILE}"
    ;;
  *)
    usage
    exit 2
    ;;
esac
