#!/usr/bin/env bash
# deploy-role.sh — Download and deploy the plainfra-ReadOnly role into a
# customer AWS account. Hosted on S3 alongside customer-role.yaml and
# invoked by the "Option A: CloudShell" path in signup.html.
#
# Usage:
#   curl -sL https://triont-plainfra-onboarding-121754142582.s3.ap-southeast-2.amazonaws.com/deploy-role.sh | bash -s <ExternalId> [ec2|full]
#
# The optional second argument selects the template: "ec2" deploys the
# EC2-only lite role (customer-role-lite.yaml), "full" (the default) deploys
# the full read-only role. Both deploy the same plainfra-ReadOnly stack, so
# re-running with "full" upgrades a lite install in place.

set -euo pipefail

EXTERNAL_ID="${1:?Usage: bash deploy-role.sh <ExternalId> [ec2|full]}"
SCOPE="${2:-full}"
# The current plainfra platform account, post-migration (see
# docs/ACCOUNT-MIGRATION-PLAN.md). If a rollback to the old management
# account (921514166437) is ever needed, trust is restored by hand in each
# already-installed customer role rather than by a default here.
PLAINFRA_ACCOUNTS="121754142582"
# The bucket this script is itself served from. S3 bucket names are globally
# unique, so the destination account uses a suffixed name (see BucketSuffix in
# infra/template.yaml) - this literal must be re-pointed and the file re-synced
# in the same change, or CloudShell installs download the wrong templates.
BUCKET="https://triont-plainfra-onboarding-121754142582.s3.ap-southeast-2.amazonaws.com"
case "${SCOPE}" in
  ec2)  TEMPLATE="customer-role-lite.yaml" ;;
  full) TEMPLATE="customer-role.yaml" ;;
  *)    echo "Unknown scope '${SCOPE}' — use ec2 or full" >&2; exit 1 ;;
esac
STACK_NAME="plainfra-ReadOnly"

echo "Downloading ${TEMPLATE}..."
curl -sO "${BUCKET}/${TEMPLATE}"

echo "Deploying ${STACK_NAME} stack..."
aws cloudformation deploy \
  --template-file "${TEMPLATE}" \
  --stack-name "${STACK_NAME}" \
  --capabilities CAPABILITY_NAMED_IAM \
  --parameter-overrides \
      "ExternalId=${EXTERNAL_ID}" \
      "PlainfraAccountIds=${PLAINFRA_ACCOUNTS}"

echo "Done — plainfra-ReadOnly role deployed. Return to the plainfra signup page and click Check Connection."
