#!/usr/bin/env bash
set -euo pipefail

cd "$(dirname "$0")/.."
source deploy/env.sh

GIT_SHA=$(git rev-parse --short HEAD 2>/dev/null || date +%s)
BASE_TAG=${BUILD_TAG:-$GIT_SHA}

# Optional dev override: set FORCE_DEV_TAG=1 to append a timestamp without committing
if [[ -n "${FORCE_DEV_TAG:-}" ]]; then
  BASE_TAG="${BASE_TAG}-dev$(date +%s)"
fi

IMAGE_REPO="${REGISTRY}/${REGISTRY_REPO}"
IMAGE="${IMAGE_REPO}:${BASE_TAG}"
IMAGE_LATEST="${IMAGE_REPO}:latest"

echo "Building image:"
echo "  $IMAGE"
echo "  $IMAGE_LATEST"

# npm audit (high severity and above)
echo "Running npm audit (high)..."
npm audit --audit-level=high || echo "npm audit reported issues above."

# Build
docker build --build-arg APP_VERSION="$GIT_SHA" -t "$IMAGE" -t "$IMAGE_LATEST" .

echo "$IMAGE" > deploy/.last-image

echo "Done. Last image: $IMAGE"

# Trivy image scan (if available)
if command -v trivy >/dev/null 2>&1; then
  MIN_TRIVY_VERSION="0.56.0"
  INSTALLED_TRIVY_VERSION="$(trivy --version 2>/dev/null | head -n1 | awk '{print $2}')"
  if [[ -n "$INSTALLED_TRIVY_VERSION" ]] && [[ "$(printf '%s\n%s\n' "$MIN_TRIVY_VERSION" "$INSTALLED_TRIVY_VERSION" | sort -V | head -n1)" != "$MIN_TRIVY_VERSION" ]]; then
    echo "Trivy version $INSTALLED_TRIVY_VERSION is older than recommended $MIN_TRIVY_VERSION."
    echo "Update recommended: brew upgrade trivy   # macOS"
    echo "or:         sudo apt-get install -y trivy   # Debian/Ubuntu (Aqua repo)"
    echo "or:         curl -sfL https://raw.githubusercontent.com/aquasecurity/trivy/main/contrib/install.sh | sudo sh -s -- -b /usr/local/bin"
  fi

  echo "Running Trivy scan on $IMAGE ..."
  TRIVY_IGNORE_ARGS=()
  if [[ -f ".trivyignore" ]]; then
    TRIVY_IGNORE_ARGS+=(--ignorefile .trivyignore)
  fi
  trivy image --exit-code 0 "${TRIVY_IGNORE_ARGS[@]}" "$IMAGE" || true
else
  echo "Trivy not installed; skipping image scan."
fi
