#!/usr/bin/env bash
# Run on the machine where kubectl is configured, outside the image build.
set +x
set -euo pipefail
umask 077

namespace="${1:-eodata-demo}"
credentials_file="$(mktemp "${TMPDIR:-/tmp}/eodata-credentials.XXXXXX")"
trap 'rm -f -- "$credentials_file"' EXIT
trap 'exit 130' INT
trap 'exit 143' TERM

IFS= read -r -s -p 'EODATA access key: ' access_key
printf '\n'
IFS= read -r -s -p 'EODATA secret key: ' secret_key
printf '\n'

if [[ -z "$access_key" || -z "$secret_key" ||
      "$access_key" =~ [[:space:]] || "$secret_key" =~ [[:space:]] ]]; then
    printf 'Both keys must be nonempty and contain no whitespace. Copy them again.\n' >&2
    exit 1
fi

printf 'AWS_ACCESS_KEY_ID=%s\nAWS_SECRET_ACCESS_KEY=%s\n' \
    "$access_key" "$secret_key" > "$credentials_file"
unset access_key secret_key

kubectl -n "$namespace" create secret generic eodata-credentials \
    --from-env-file="$credentials_file"
