#!/usr/bin/env bash

set -euo pipefail

ROOT_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)
DEPLOY_SCRIPT="$ROOT_DIR/scripts/deploy-images.sh"
CALL_LOG=$(mktemp)
trap 'rm -f "$CALL_LOG"' EXIT

OLD_BACKEND='registry.local/magistr-backend@sha256:1111111111111111111111111111111111111111111111111111111111111111'
OLD_FRONTEND='registry.local/magistr-frontend@sha256:2222222222222222222222222222222222222222222222222222222222222222'
NEW_BACKEND='registry.local/magistr-backend@sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'
NEW_FRONTEND='registry.local/magistr-frontend@sha256:bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb'

kubectl() {
    printf '%s\n' "$*" >> "$CALL_LOG"
    if [[ "$1" == "get" && "$3" == "backend" ]]; then
        printf '%s' "$OLD_BACKEND"
        return 0
    fi
    if [[ "$1" == "get" && "$3" == "frontend" ]]; then
        printf '%s' "$OLD_FRONTEND"
        return 0
    fi
    if [[ "${DEPLOY_TEST_MODE:-success}" == "failure" \
            && "$1" == "rollout" \
            && "$3" == "deployment/backend" \
            && "${DEPLOY_TEST_FAILURE_EMITTED:-false}" == "false" ]]; then
        DEPLOY_TEST_FAILURE_EMITTED=true
        return 1
    fi
    return 0
}
export -f kubectl
export CALL_LOG OLD_BACKEND OLD_FRONTEND DEPLOY_TEST_MODE DEPLOY_TEST_FAILURE_EMITTED

if bash "$DEPLOY_SCRIPT" 'registry.local/backend:main' "$NEW_FRONTEND" >/dev/null 2>&1; then
    printf 'Ошибка теста: mutable backend tag не был отклонён\n' >&2
    exit 1
fi

: > "$CALL_LOG"
DEPLOY_TEST_MODE=success bash "$DEPLOY_SCRIPT" "$NEW_BACKEND" "$NEW_FRONTEND"
grep --fixed-strings "set image deployment/backend backend=$NEW_BACKEND" "$CALL_LOG" >/dev/null
grep --fixed-strings "set image deployment/frontend frontend=$NEW_FRONTEND" "$CALL_LOG" >/dev/null

: > "$CALL_LOG"
if DEPLOY_TEST_MODE=failure DEPLOY_TEST_FAILURE_EMITTED=false \
        bash "$DEPLOY_SCRIPT" "$NEW_BACKEND" "$NEW_FRONTEND"; then
    printf 'Ошибка теста: неуспешный rollout завершился кодом 0\n' >&2
    exit 1
fi
grep --fixed-strings "set image deployment/backend backend=$OLD_BACKEND" "$CALL_LOG" >/dev/null
grep --fixed-strings "set image deployment/frontend frontend=$OLD_FRONTEND" "$CALL_LOG" >/dev/null

printf 'Проверка immutable rollout и rollback завершена успешно\n'
