#!/usr/bin/env bash
# Run only on an isolated, trusted, rootless-Podman agent.
set -euo pipefail
: "${AWS_REGION:?}" "${ECR_REPOSITORY:?}" "${BUILD_NUMBER:?}"
[[ "$ECR_REPOSITORY" =~ ^[a-z0-9][a-z0-9/_-]+$ ]]
[[ "$BUILD_NUMBER" =~ ^[0-9]+$ ]]
[[ "$(podman info --format '{{.Host.Security.Rootless}}')" == true ]]
commit=$(git rev-parse HEAD)
[[ "$commit" =~ ^[0-9a-f]{40}$ ]]
account=$(aws sts get-caller-identity --query Account --output text)
[[ "$account" =~ ^[0-9]{12}$ ]]
registry="$account.dkr.ecr.$AWS_REGION.amazonaws.com"
repo="$registry/$ECR_REPOSITORY"
tag="$commit-$BUILD_NUMBER"
work=$(mktemp -d)
trap 'rm -rf "$work"' EXIT
export REGISTRY_AUTH_FILE="$work/auth.json"
mkdir -p audit
# Registry is pre-created with immutable tags; never change that policy here.
aws ecr describe-repositories --repository-names "$ECR_REPOSITORY" --query 'repositories[0].imageTagMutability' --output text | grep -qx IMMUTABLE
aws ecr get-login-password --region "$AWS_REGION" |
  podman login --username AWS --password-stdin "$registry" >/dev/null
set --
if [[ "${APP_KIND:-}" == python ]]; then
  : "${BASE_IMAGE:?Approved Python base image digest required}"
  [[ "$BASE_IMAGE" =~ @sha256:[0-9a-f]{64}$ ]]
  set -- --build-arg "BASE_IMAGE=$BASE_IMAGE"
fi
podman build "$@" --pull=always --label "org.opencontainers.image.revision=$commit" -t "$repo:$tag" .
if [[ "${APP_KIND:-}" == python ]]; then
  CONTAINER_ENGINE=podman RUN_PROJECT="orders-ci-${BUILD_NUMBER}" ORDERS_IMAGE="$repo:$tag" TEST_EXISTING_IMAGE=true bash ci/test.sh
fi
podman save --format oci-archive -o "$work/image.tar" "$repo:$tag"
# Scanner and vulnerability database must be available; network/errors fail the build.
trivy image --input "$work/image.tar" --exit-code 1 --severity HIGH,CRITICAL --format json --output audit/image-scan.json
podman push --digestfile "$work/digest" "$repo:$tag"
digest=$(cat "$work/digest")
[[ "$digest" =~ ^sha256:[0-9a-f]{64}$ ]]
remote=$(aws ecr describe-images --repository-name "$ECR_REPOSITORY" --image-ids "imageTag=$tag" --query 'imageDetails[0].imageDigest' --output text)
[[ "$remote" == "$digest" ]]
printf '%s@%s\n' "$repo" "$digest" > audit/image.txt
printf '%s\n' "$commit" > audit/commit.txt
