#!/usr/bin/env bash
# Capstone 5, DevSecOps: tests -> static analysis -> dependency audit -> secrets -> image scan -> SBOM
# -> signing and attestation -> policy -> deploy only what is signed.
# A local registry listens on 5002 and the service on 18085.
source "$(dirname "$0")/../lib.sh"
need docker trivy syft jq curl python3
work devsecops
export REG="localhost:${REG_PORT:-5002}"
port_free "${REG_PORT:-5002}"; port_free "${PORT:-18085}"
mkdir -p "$WORK/src/k8s"
cp "$APP_SRC/orders.py" "$APP_SRC/test_orders.py" "$APP_SRC/Dockerfile" "$CAP_ROOT/05-devsecops/requirements-ci.txt" "$WORK/src/"
cp "$CAP_ROOT/05-devsecops/k8s/deploy.yaml" "$WORK/src/k8s/"
cd "$WORK"

say "1. Install the pinned pipeline tools in a virtual environment"
python3 -m venv .venv
.venv/bin/pip install -q --disable-pip-version-check -r src/requirements-ci.txt
.venv/bin/bandit --version | head -1
.venv/bin/pip-audit --version

say "2. Start a local registry and create a signing key pair"
docker run -d --name cap-sec-registry -p "127.0.0.1:${REG_PORT:-5002}:5000" registry:2.8.3 > /dev/null
wait_for "http://$REG/v2/" 20
# a throwaway key with an empty password, for this lab only; real keys live in a KMS, or use keyless signing
export COSIGN_PASSWORD=""
docker run --rm -u 0 -v "$WORK:/w" -w /w -e COSIGN_PASSWORD gcr.io/projectsigstore/cosign:v2.4.1 generate-key-pair > /dev/null 2>&1
ls cosign.key cosign.pub

say "3. Run the pipeline"
bash "$CAP_ROOT/05-devsecops/pipeline.sh" src 1.0.0
