#!/usr/bin/env bash
# Schedule Lambda Managed Instances capacity for predictable peaks.
# Context: EventBridge Scheduler → PutFunctionScalingConfig (May 2026 GA).
# Requires: AWS CLI v2, IAM role with lambda:PutFunctionScalingConfig + scheduler:CreateSchedule.
# Usage: ./put-function-scaling-scheduler.sh <function-name> <account-id> <region>

set -euo pipefail

FUNCTION_NAME="${1:?function name required}"
ACCOUNT_ID="${2:?account id required}"
REGION="${3:-us-east-1}"
ROLE_ARN="arn:aws:iam::${ACCOUNT_ID}:role/eventbridge-scheduler-lambda-scaling"

# Scale up Mon–Fri 08:00 UTC — baseline peak capacity
aws scheduler create-schedule \
  --region "$REGION" \
  --name "lmi-scale-up-${FUNCTION_NAME}" \
  --schedule-expression "cron(0 8 ? * MON-FRI *)" \
  --flexible-time-window '{"Mode":"OFF"}' \
  --target "{
    \"Arn\": \"arn:aws:scheduler:::aws-sdk:lambda:PutFunctionScalingConfig\",
    \"RoleArn\": \"${ROLE_ARN}\",
    \"Input\": \"{\\\"FunctionName\\\":\\\"${FUNCTION_NAME}\\\",\\\"Qualifier\\\":\\\"\\$LATEST.PUBLISHED\\\",\\\"FunctionScalingConfig\\\":{\\\"MinExecutionEnvironments\\\":20,\\\"MaxExecutionEnvironments\\\":200}}\"
  }"

# Scale down Mon–Fri 18:00 UTC — idle floor (set 0/0 to fully deactivate)
aws scheduler create-schedule \
  --region "$REGION" \
  --name "lmi-scale-down-${FUNCTION_NAME}" \
  --schedule-expression "cron(0 18 ? * MON-FRI *)" \
  --flexible-time-window '{"Mode":"OFF"}' \
  --target "{
    \"Arn\": \"arn:aws:scheduler:::aws-sdk:lambda:PutFunctionScalingConfig\",
    \"RoleArn\": \"${ROLE_ARN}\",
    \"Input\": \"{\\\"FunctionName\\\":\\\"${FUNCTION_NAME}\\\",\\\"Qualifier\\\":\\\"\\$LATEST.PUBLISHED\\\",\\\"FunctionScalingConfig\\\":{\\\"MinExecutionEnvironments\\\":3,\\\"MaxExecutionEnvironments\\\":20}}\"
  }"

echo "Schedules created. Verify with: aws scheduler list-schedules --region ${REGION} --name-prefix lmi-scale"
