#!/bin/sh set -eu ROOT=$(CDPATH='' cd -- "$(dirname -- "$0")/.." && pwd) if [ "$#" -ne 2 ]; then echo "Usage: $0 ENV_FILE FCM_SERVICE_ACCOUNT_JSON" >&2 exit 1 fi env_file=$1 service_account_file=$2 if [ ! -f "$service_account_file" ]; then echo "FCM service-account JSON does not exist: $service_account_file" >&2 exit 1 fi case "$(stat -c '%a' "$service_account_file")" in 400|600) ;; *) echo "FCM service-account JSON contains a private key and must have mode 0400 or 0600." >&2 exit 1 ;; esac if ! jq --exit-status ' .type == "service_account" and (.project_id | type == "string" and length > 0 and test("^[^\r\n]+$")) and (.client_email | type == "string" and length > 0 and test("^[^\r\n]+$")) and (.private_key | type == "string" and length > 0) ' "$service_account_file" >/dev/null; then echo "FCM service-account JSON is incomplete." >&2 exit 1 fi project_id=$(jq --raw-output '.project_id' "$service_account_file") firebase_project_id=$( awk -F= ' $1 == "WNH_FIREBASE_PROJECT_ID" { print substr($0, index($0, "=") + 1) exit } ' "$env_file" ) if [ -n "$firebase_project_id" ] && [ "$firebase_project_id" != "$project_id" ]; then echo "FCM service-account project does not match WNH_FIREBASE_PROJECT_ID." >&2 exit 1 fi values_file=$(mktemp "${TMPDIR:-/tmp}/wnh-fcm-service-account-values.XXXXXX") trap 'rm -f "$values_file"' EXIT HUP INT TERM chmod 600 "$values_file" { printf 'FCM_PROJECT_ID=%s\n' "$project_id" printf 'FCM_SERVICE_ACCOUNT_FILE=\n' printf 'FCM_SERVICE_ACCOUNT_JSON_BASE64=' base64 -w 0 "$service_account_file" printf '\n' } >"$values_file" "$ROOT/scripts/set-env-values.sh" "$env_file" "$values_file" >/dev/null echo "FCM service account imported without printing the private key." echo "The downloaded JSON still contains the private key; store or remove it deliberately."