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

usage() {
  printf 'usage: pem-to-env VARIABLE_NAME path/to/key.pem\n' >&2
  exit 2
}

[[ "$#" -eq 2 ]] || usage

name="$1"
file="$2"

case "$name" in
  [A-Za-z_][A-Za-z0-9_]*) ;;
  *) printf 'pem-to-env: invalid environment variable name: %s\n' "$name" >&2; exit 2 ;;
esac

[[ -f "$file" ]] || {
  printf 'pem-to-env: file not found: %s\n' "$file" >&2
  exit 1
}

printf '%s="' "$name"
awk 'NF { gsub(/\r/, ""); gsub(/\\/,"\\\\"); gsub(/"/,"\\\""); printf "%s\\n", $0 }' "$file"
printf '"\n'
