#!/usr/bin/env bash
# shellcheck disable=SC2155
set -eo pipefail

# Selects post-update checks from Pulumi changes; Git release detection only gates CI builds and manual rollouts.

readonly APP_CONFIG="area/apps/apps.hjson"
readonly APP_MAKE_DIR="area/apps"
readonly LOAD_DURATION="30s"
readonly LOAD_SUCCESS_RATIO="1"
readonly SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
readonly REPO_ROOT="$(git -C "$SCRIPT_DIR" rev-parse --show-toplevel)"
readonly UPDATE_SELECTION="$REPO_ROOT/$APP_MAKE_DIR/.release-selection.json"
readonly VERIFY_CONNECT_TIMEOUT="5"
readonly VERIFY_MAX_TIME="30"
readonly -a APPS=(standort bezeichner web abgleich einblick)

# Prints command usage.
usage() {
  printf 'Usage: %s <update|halt-ci|is-release>\n' "$0" >&2
  printf '       %s <kube-score|kubescape|images|load|rollout|verify>[-all|-<app>]\n' "$0" >&2
}

# Invalidate the previous selection before any update, including failed or interrupted attempts.
update_apps() (
  local events
  local revision

  if [[ "${APPS_RELEASE_DRY_RUN:-}" == "true" ]]; then
    printf 'pulumi update --yes --stack alexfalkowski/apps/prod --cwd %s --json\n' "$APP_MAKE_DIR"
    return
  fi

  printf 'null\n' > "$UPDATE_SELECTION"
  revision="$(git -C "$REPO_ROOT" rev-parse HEAD)"
  events="$(mktemp)"
  trap 'rm -f "$events"' EXIT

  pulumi update --yes --stack alexfalkowski/apps/prod --cwd "$REPO_ROOT/$APP_MAKE_DIR" --json \
    | tee "$events" \
    | jq --unbuffered -r '
      if .diagnosticEvent then .diagnosticEvent.message
      elif .resourcePreEvent then
        .resourcePreEvent | select(.planning != true) | .metadata | "\(.op) \(.urn)"
      elif .summaryEvent then .summaryEvent | "Update summary: \(.resourceChanges)"
      else empty end
    '

  jq -s --arg revision "$revision" --arg apps "${APPS[*]}" '
    def owner:
      (.new.inputs.metadata // .new.outputs.metadata // .old.inputs.metadata // .old.outputs.metadata // {})
      | .labels["app.kubernetes.io/name"] // "";
    def images($state):
      [$state.inputs.spec.template.spec | (.containers[]?, .initContainers[]?) | {name, image}]
      | sort_by(.name, .image);

    ($apps | split(" ")) as $supported |
    [.[] | .summaryEvent // empty | select(.isPreview == false)] as $summaries |
    if ($summaries | length) != 1 or $summaries[0].maybeCorrupt != false
      or ($summaries[0].result // "succeeded") != "succeeded"
      or any(.[]; .resOpFailedEvent != null or .errorEvent != null)
    then error("missing or unsuccessful Pulumi update summary") else . end |
    [.[] | .resOutputsEvent // empty | select(.planning != true) | .metadata] as $steps |
    [$steps[] | select(.op != "same" and .op != "read" and .op != "read-replacement")
      | select((.type | startswith("kubernetes:")) or .type == "pulumi:providers:kubernetes")
    ] as $changed |
    if any($changed[]; . as $step |
      (["create", "update", "replace", "create-replacement", "delete", "delete-replaced",
        "import", "import-replacement"] | index($step.op)) == null)
    then error("unsupported Pulumi resource operation") else . end |
    if any($changed[]; owner as $name | $name != "" and ($supported | index($name)) == null)
    then error("changed application has no release helpers") else . end |
    if any($changed[]; (.new.inputs.metadata.namespace // .old.inputs.metadata.namespace // "lean") != "lean")
    then error("changed application is outside the supported lean namespace") else . end |
    any($changed[]; owner as $name |
      .type == "pulumi:providers:kubernetes" or $name == "" or
      (.type == "kubernetes:networking.k8s.io/v1:NetworkPolicy" and
        (.new.inputs.spec // .old.inputs.spec).podSelector.matchLabels.app != $name) or
      (.type == "kubernetes:policy/v1:PodDisruptionBudget" and
        (.new.inputs.spec // .old.inputs.spec).selector.matchLabels.app != $name)
    ) as $shared |
    [$changed[] | select(.type == "kubernetes:apps/v1:Deployment" and .op == "delete") | owner] as $deleted |
    [$steps[] | select(.type == "kubernetes:apps/v1:Deployment" and .new != null and
      .op != "delete" and .op != "delete-replaced") | owner] as $present |
    ($deleted - $present) as $removed |
    {
      revision: $revision,
      shared: $shared,
      apps: ((if $shared then $supported else [$changed[] | owner | select(. != "")] end) - $removed | unique),
      inactive: [$steps[] | select(.type == "kubernetes:apps/v1:Deployment" and .new != null and
        (.new.inputs.spec.replicas // 1) == 0) | owner] | unique,
      images: ([$changed[] | select(.type == "kubernetes:apps/v1:Deployment" and .new != null and
        .op != "delete" and .op != "delete-replaced" and images(.old) != images(.new)) | owner]
        - $removed | unique)
    }
  ' "$events" > "$UPDATE_SELECTION"
)

# A missing, partial, or stale update must never be interpreted as an empty successful selection.
update_selection() {
  if [[ ! -s "$UPDATE_SELECTION" ]]; then
    printf 'missing update selection; run make area=apps pulumi-update or use an explicit *-all/per-app check\n' >&2
    return 1
  fi

  jq -se --arg revision "$(git -C "$REPO_ROOT" rev-parse HEAD)" --arg apps "${APPS[*]}" '
    if length != 1 then error("invalid update selection") else .[0] end |
    ($apps | split(" ")) as $supported |
    if .revision == $revision and (.shared | type) == "boolean" and
      (.apps | type) == "array" and (.images | type) == "array" and (.inactive | type) == "array" and
      all((.apps[], .images[], .inactive[]); . as $name | ($supported | index($name)) != null) and
      ((.images - .apps) | length) == 0
    then . else error("invalid or stale update selection; run make area=apps pulumi-update") end
  ' "$UPDATE_SELECTION"
}

run_update_changes() {
  local action
  local app
  local apps
  local selection

  action="$1"
  selection="$(update_selection)"
  if [[ "$action" == "kube-score" || "$action" == "kubescape" ]]; then
    if [[ "$(jq -r '.shared' <<< "$selection")" == "true" ]]; then
      if [[ "${APPS_RELEASE_DRY_RUN:-}" == "true" ]]; then
        printf 'make -C %s %s-lean\n' "$APP_MAKE_DIR" "$action"
      else
        make -C "$REPO_ROOT/$APP_MAKE_DIR" "${action}-lean"
      fi
      return
    fi
  fi

  apps="$(jq -r --arg action "$action" '
    if $action == "images" then .images
    elif $action == "load" or $action == "verify" then .apps - .inactive
    else .apps end | .[]
  ' <<< "$selection")"
  if [[ -z "$apps" ]]; then
    printf '%s: skipped; no relevant changes in the last update.\n' "$action"
    return
  fi

  while IFS= read -r app; do
    printf '%s changed app: %s\n' "$action" "$app"
    run_app_action "$action" "$app"
  done <<< "$apps"
}

# Prints the revision to inspect for app release changes.
head_revision() {
  printf '%s\n' "${APPS_RELEASE_HEAD:-HEAD}"
}

# Prints the revision to compare against the inspected revision.
base_revision() {
  local head

  head="$(head_revision)"
  if [[ -n "${APPS_RELEASE_BASE:-}" ]]; then
    printf '%s\n' "$APPS_RELEASE_BASE"
    return
  fi

  if git -C "$REPO_ROOT" rev-parse --verify "${head}^" >/dev/null 2>&1; then
    printf '%s\n' "${head}^"
    return
  fi

  if git -C "$REPO_ROOT" rev-parse --verify origin/master >/dev/null 2>&1; then
    printf '%s\n' "origin/master"
    return
  fi

  printf 'could not determine release diff base\n' >&2
  return 1
}

# Reports whether the inspected diff only touches the apps config.
has_only_app_config_changed() {
  local base
  local changed
  local head

  base="$(base_revision)"
  head="$(head_revision)"
  changed="$(git -C "$REPO_ROOT" diff --name-only "$base" "$head" --)"

  [[ "$changed" == "$APP_CONFIG" ]]
}

# Reports whether the apps config diff only changes application version fields.
has_only_application_versions_changed() {
  local base
  local head

  base="$(base_revision)"
  head="$(head_revision)"

  git -C "$REPO_ROOT" diff --unified=0 --no-ext-diff --no-color "$base" "$head" -- "$APP_CONFIG" \
    | awk '
      BEGIN { valid = 1 }
      /^(---|\+\+\+|@@)/ { next }
      /^[-+]/ {
        seen = 1
        if ($0 !~ /^[-+][[:space:]]+version:[[:space:]]+[0-9]+\.[0-9]+\.[0-9]+$/) {
          valid = 0
        }
      }
      END {
        if (!seen || !valid) {
          exit 1
        }
      }
    '
}

# Reports whether the inspected diff is a release-only apps change.
has_release_only_changes() {
  has_only_app_config_changed && has_only_application_versions_changed
}

# Prints application names with changed release versions.
changed_release_apps() {
  local base
  local head

  base="$(base_revision)"
  head="$(head_revision)"

  git -C "$REPO_ROOT" diff --unified=80 --no-ext-diff --no-color "$base" "$head" -- "$APP_CONFIG" \
    | awk '
      /^[ +][[:space:]]+name:[[:space:]]/ { name = $2 }
      /^\+[[:space:]]+version:[[:space:]]+[0-9]+\.[0-9]+\.[0-9]+$/ && name != "" { print name }
    ' \
    | sort -u
}

# Prints release-only changed apps, or fails when the diff is not targeted.
release_apps() {
  local app
  local apps=()

  if ! has_release_only_changes; then
    return 1
  fi

  while IFS= read -r app; do
    [[ -n "$app" ]] && apps+=("$app")
  done < <(changed_release_apps)

  ((${#apps[@]} > 0)) || return 1
  printf '%s\n' "${apps[@]}"
}

# Reports whether an app has release helper commands.
is_app() {
  case "$1" in
    abgleich | bezeichner | einblick | standort | web)
      return 0
      ;;
    *)
      return 1
      ;;
  esac
}

# Reports whether an app action has release helper commands.
is_action() {
  case "$1" in
    kube-score | kubescape | images | load | rollout | verify)
      return 0
      ;;
    *)
      return 1
      ;;
  esac
}

# Runs an app action, or prints it when dry-run mode is enabled.
run_app_action() {
  local action
  local app
  local manifest_dir

  action="$1"
  app="$2"

  if ! is_action "$action"; then
    printf 'invalid action: %s\n' "$action" >&2
    return 1
  fi

  if ! is_app "$app"; then
    printf 'invalid app name: %s\n' "$app" >&2
    return 1
  fi

  if [[ "$action" == "load" && ( "$app" == "abgleich" || "$app" == "einblick" ) ]]; then
    printf 'load %s: skipped; no load scenario.\n' "$app"
    return
  fi

  if [[ "${APPS_RELEASE_DRY_RUN:-}" == "true" ]]; then
    printf './%s/release %s-%s\n' "$APP_MAKE_DIR" "$action" "$app"
    return
  fi

  case "$action" in
    kube-score)
      "$SCRIPT_DIR/kube-score" lean "$app"
      ;;
    kubescape)
      (
        manifest_dir="$(mktemp -d)"
        trap 'rm -rf -- "$manifest_dir"' EXIT
        "$SCRIPT_DIR/manifests" lean "$app" > "$manifest_dir/manifests.yaml"
        "$SCRIPT_DIR/kubescape" "$manifest_dir/manifests.yaml"
      )
      ;;
    images)
      scan_app_images "$app"
      ;;
    *)
      "${action}_${app}"
      ;;
  esac
}

# Runs an app action for every supported app.
run_all_apps() {
  local action
  local app

  action="$1"
  if ! is_action "$action"; then
    printf 'invalid action: %s\n' "$action" >&2
    return 1
  fi

  for app in "${APPS[@]}"; do
    run_app_action "$action" "$app"
  done
}

# Runs a release-aware app action and falls back to all apps or a supplied action.
run_release_changes() {
  local action
  local app
  local apps=()
  local fallback
  local label

  action="$1"
  label="$2"
  fallback="${3:-}"

  while IFS= read -r app; do
    [[ -n "$app" ]] && apps+=("$app")
  done < <(release_apps || true)

  if ((${#apps[@]} == 0)); then
    printf '%s all apps.\n' "$label"
    if [[ -n "$fallback" ]]; then
      "$fallback"
      return
    fi

    run_all_apps "$action"
    return
  fi

  for app in "${apps[@]}"; do
    if ! is_app "$app"; then
      printf 'invalid app name: %s\n' "$app" >&2
      return 1
    fi

    printf '%s release app: %s\n' "$label" "$app"
    run_app_action "$action" "$app"
  done
}

# Verifies that a Vegeta result file meets the deploy gate threshold.
assert_successful_load() {
  local result

  result="$1"
  vegeta report -type=json "$result" \
    | awk -v threshold="$LOAD_SUCCESS_RATIO" '
      match($0, /"success":[[:space:]]*[0-9.]+/) {
        success = substr($0, RSTART + 10, RLENGTH - 10)
      }
      END {
        if (success == "") {
          print "could not read vegeta success ratio" > "/dev/stderr"
          exit 1
        }
        if (success + 0 < threshold + 0) {
          printf "load success ratio %.2f%% is below %.2f%%\n", success * 100, threshold * 100 > "/dev/stderr"
          exit 1
        }
      }
    '
}

# Load tests all apps.
load_all() {
  run_all_apps "load"
}

# Load tests standort.
load_standort() {
  local result

  result="$REPO_ROOT/$APP_MAKE_DIR/lean/standort.bin"
  printf 'POST https://standort.lean-thoughts.com/standort.v2.Service/GetLocation\n' \
    | vegeta attack -duration="$LOAD_DURATION" \
      -body "$REPO_ROOT/$APP_MAKE_DIR/lean/standort.json" \
      -header "Content-Type: application/json" \
    | tee "$result" \
    | vegeta report
  assert_successful_load "$result"
}

# Load tests bezeichner.
load_bezeichner() {
  local result

  result="$REPO_ROOT/$APP_MAKE_DIR/lean/bezeichner.bin"
  printf 'POST https://bezeichner.lean-thoughts.com/bezeichner.v1.Service/GenerateIdentifiers\n' \
    | vegeta attack -duration="$LOAD_DURATION" \
      -body "$REPO_ROOT/$APP_MAKE_DIR/lean/bezeichner.json" \
      -header "Content-Type: application/json" \
    | tee "$result" \
    | vegeta report
  assert_successful_load "$result"
}

# Load tests web.
load_web() {
  local result

  result="$REPO_ROOT/$APP_MAKE_DIR/lean/web.bin"
  printf 'GET https://web.lean-thoughts.com\n' \
    | vegeta attack -duration="$LOAD_DURATION" \
    | tee "$result" \
    | vegeta report
  assert_successful_load "$result"
}

# Load eligibility is independent of the Git release-only build optimization.
load_release_changes() {
  run_update_changes "load"
}

# Scans all apps in the namespace with kubescape.
kubescape_all() {
  if [[ "${APPS_RELEASE_DRY_RUN:-}" == "true" ]]; then
    printf 'make -C %s kubescape-lean\n' "$APP_MAKE_DIR"
  else
    make -C "$REPO_ROOT/$APP_MAKE_DIR" kubescape-lean
  fi
}

# Image scans are explicit operator actions, separate from deployment lint.
scan_app_images() {
  local app
  local image
  local images

  app="$1"
  images="$(kubectl get deployment "$app" --namespace lean --output json \
    | jq -er '[.spec.template.spec | (.containers[]?, .initContainers[]?) | .image] | unique | .[]')"
  while IFS= read -r image; do
    kubescape scan image "$image"
  done <<< "$images"
}

# Rolls out all apps.
rollout_all() {
  run_all_apps "rollout"
}

rollout_abgleich() {
  kubectl rollout restart deployment/abgleich -n lean
}

rollout_einblick() {
  kubectl rollout restart deployment/einblick -n lean
}

# Rolls out standort.
rollout_standort() {
  kubectl rollout restart deployment/standort -n lean
}

# Rolls out bezeichner.
rollout_bezeichner() {
  kubectl rollout restart deployment/bezeichner -n lean
}

# Rolls out web.
rollout_web() {
  kubectl rollout restart deployment/web -n lean
}

# Rolls out targeted release apps and falls back to the full apps rollout target.
rollout_release_changes() {
  run_release_changes "rollout" "Rolling out"
}

# Verifies all apps.
verify_all() {
  run_all_apps "verify"
}

# Skips public URL verification for Abgleich.
verify_abgleich() {
  printf 'verify abgleich: skipped; no URL check required.\n'
}

# Verifies Einblick readiness until telemetry workflows are implemented.
verify_einblick() {
  curl -svf \
    --connect-timeout "$VERIFY_CONNECT_TIMEOUT" \
    --max-time "$VERIFY_MAX_TIME" \
    https://einblick.lean-thoughts.com/einblick/readyz
}

# Verifies standort.
verify_standort() {
  curl -svf \
    --connect-timeout "$VERIFY_CONNECT_TIMEOUT" \
    --max-time "$VERIFY_MAX_TIME" \
    --header "Content-Type: application/json" \
    --request POST \
    --data "{}" \
    https://standort.lean-thoughts.com/standort.v2.Service/GetLocation
}

# Verifies bezeichner.
verify_bezeichner() {
  curl -svf \
    --connect-timeout "$VERIFY_CONNECT_TIMEOUT" \
    --max-time "$VERIFY_MAX_TIME" \
    --header "Content-Type: application/json" \
    --request POST \
    --data '{ "application": "ulid", "count": 10 }' \
    https://bezeichner.lean-thoughts.com/bezeichner.v1.Service/GenerateIdentifiers
}

# Verifies web.
verify_web() {
  curl -svf \
    --connect-timeout "$VERIFY_CONNECT_TIMEOUT" \
    --max-time "$VERIFY_MAX_TIME" \
    https://web.lean-thoughts.com
}

# Verify only workloads that the successful update affected and left running.
verify_release_changes() {
  run_update_changes "verify"
}

# Halts CircleCI for release-only app changes.
halt_ci() {
  if ! release_apps >/dev/null; then
    return
  fi

  if [[ "${APPS_RELEASE_DRY_RUN:-}" == "true" ]]; then
    printf 'circleci-agent step halt\n'
    return
  fi

  circleci-agent step halt
}

case "${1:-}" in
  update)
    update_apps
    ;;
  halt-ci)
    halt_ci
    ;;
  is-release)
    release_apps >/dev/null
    ;;
  kube-score)
    run_update_changes "kube-score"
    ;;
  kube-score-all)
    if [[ "${APPS_RELEASE_DRY_RUN:-}" == "true" ]]; then
      printf 'make -C %s kube-score-lean\n' "$APP_MAKE_DIR"
    else
      make -C "$REPO_ROOT/$APP_MAKE_DIR" kube-score-lean
    fi
    ;;
  kubescape)
    run_update_changes "kubescape"
    ;;
  kubescape-all)
    kubescape_all
    ;;
  images)
    run_update_changes "images"
    ;;
  images-all)
    run_all_apps "images"
    ;;
  load)
    load_release_changes
    ;;
  load-all)
    load_all
    ;;
  rollout)
    rollout_release_changes
    ;;
  rollout-all)
    rollout_all
    ;;
  verify)
    verify_release_changes
    ;;
  verify-all)
    verify_all
    ;;
  kube-score-* | kubescape-* | images-* | load-* | rollout-* | verify-*)
    action="${1%-*}"
    app="${1##*-}"
    run_app_action "$action" "$app"
    ;;
  *)
    usage
    exit 2
    ;;
esac
