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

readonly PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
readonly APP_ROOT="/srv/apps/warehouse-allocation"
readonly RELEASES_DIR="${APP_ROOT}/releases"
readonly SHARED_ENV="${APP_ROOT}/shared/.env"
readonly INCOMING_DIR="/home/warehouse-deploy/incoming"
readonly IMAGE_REPOSITORY="local/warehouse-allocation"
readonly NGINX_UPSTREAM="/etc/nginx/conf.d/10-warehouse-allocation-upstream.conf"
readonly PUBLIC_URL="https://warehouse-allocation.mvphub.ir"
readonly LOCK_FILE="/run/lock/warehouse-allocation-deploy.lock"

release_id="${1:-}"
expected_checksum="${2:-}"

if [[ ! "$release_id" =~ ^[0-9a-f]{40}$ ]]; then
    echo "release id must be a full 40-character lowercase commit SHA" >&2
    exit 64
fi
if [[ ! "$expected_checksum" =~ ^[0-9a-f]{64}$ ]]; then
    echo "checksum must be a lowercase SHA-256 digest" >&2
    exit 64
fi

readonly release_id expected_checksum
readonly archive="${INCOMING_DIR}/release-${release_id}.tar.gz"
readonly release_dir="${RELEASES_DIR}/${release_id}"
readonly candidate_image="${IMAGE_REPOSITORY}:${release_id}"

exec 9>"$LOCK_FILE"
if ! flock -n 9; then
    echo "another warehouse-allocation deployment is running" >&2
    exit 75
fi

umask 077
work_dir="$(mktemp -d "${APP_ROOT}/shared/.deploy.XXXXXX")"
archive_listing="${work_dir}/archive.list"
upstream_backup="${work_dir}/upstream.conf"
openapi_file="${work_dir}/openapi.json"
example_file="${work_dir}/example.json"
response_file="${work_dir}/response.json"

candidate_started=0
upstream_changed=0
deployment_complete=0
current_changed=0
previous_release=""
active_container=""
candidate=""
candidate_port=""
active=""
blue_image=""
green_image=""
staging_dir=""

compose() {
    env \
        BLUE_IMAGE="$blue_image" \
        GREEN_IMAGE="$green_image" \
        docker compose \
        --env-file "$SHARED_ENV" \
        -f "${release_dir}/deploy/compose.server.yaml" \
        "$@"
}

env_value() {
    local key="$1"
    awk -F= -v key="$key" '$1 == key {sub(/^[^=]*=/, ""); print; exit}' "$SHARED_ENV"
}

upsert_env() {
    local key="$1"
    local value="$2"
    local temporary
    temporary="$(mktemp "${APP_ROOT}/shared/.env.XXXXXX")"
    awk -v key="$key" -v value="$value" '
        BEGIN { found = 0 }
        index($0, key "=") == 1 {
            print key "=" value
            found = 1
            next
        }
        { print }
        END {
            if (!found) {
                print key "=" value
            }
        }
    ' "$SHARED_ENV" >"$temporary"
    chmod 0600 "$temporary"
    chown root:root "$temporary"
    mv -f "$temporary" "$SHARED_ENV"
}

write_upstream() {
    local port="$1"
    local temporary
    temporary="$(mktemp "/etc/nginx/conf.d/.warehouse-allocation-upstream.XXXXXX")"
    cat >"$temporary" <<EOF
upstream warehouse_allocation_backend {
    server 127.0.0.1:${port} max_fails=3 fail_timeout=5s;
    keepalive 32;
}
EOF
    chmod 0644 "$temporary"
    chown root:root "$temporary"
    mv -f "$temporary" "$NGINX_UPSTREAM"
}

rollback() {
    local exit_code=$?
    trap - EXIT

    if ((deployment_complete == 0)); then
        echo "deployment failed; preserving the previous production slot" >&2

        if ((upstream_changed == 1)) && [[ -s "$upstream_backup" ]]; then
            cp -f "$upstream_backup" "$NGINX_UPSTREAM"
            if nginx -t; then
                systemctl reload nginx || true
            fi
        fi

        if ((current_changed == 1)) && [[ -n "$previous_release" ]]; then
            ln -sfn "$previous_release" "${APP_ROOT}/current"
        fi

        if ((candidate_started == 1)) && [[ -n "$candidate" ]]; then
            compose --profile "$candidate" stop "api-${candidate}" || true
            compose --profile "$candidate" rm -f "api-${candidate}" || true
        fi

        if [[ -n "$staging_dir" && -d "$staging_dir" ]]; then
            rm -rf "$staging_dir"
        fi
    fi

    rm -rf "$work_dir"
    exit "$exit_code"
}
trap rollback EXIT

if [[ ! -f "$archive" ]]; then
    echo "release archive is missing: $archive" >&2
    exit 66
fi
if [[ ! -f "$SHARED_ENV" ]]; then
    echo "shared production environment is missing: $SHARED_ENV" >&2
    exit 66
fi

actual_checksum="$(sha256sum "$archive" | awk '{print $1}')"
if [[ "$actual_checksum" != "$expected_checksum" ]]; then
    echo "release archive checksum mismatch" >&2
    exit 65
fi

tar -tzf "$archive" >"$archive_listing"
if grep -Eq '(^/|(^|/)\.\.(/|$))' "$archive_listing"; then
    echo "release archive contains an unsafe path" >&2
    exit 65
fi

if [[ -d "$release_dir" ]]; then
    if [[ ! -f "${release_dir}/.release-checksum" ]] ||
        [[ "$(<"${release_dir}/.release-checksum")" != "$expected_checksum" ]]; then
        echo "existing release directory does not match the artifact checksum" >&2
        exit 65
    fi
else
    staging_dir="${RELEASES_DIR}/.${release_id}.staging"
    if [[ -e "$staging_dir" ]]; then
        echo "staging directory already exists: $staging_dir" >&2
        exit 73
    fi
    install -d -m 0755 "$staging_dir"
    tar -xzf "$archive" -C "$staging_dir"
    printf '%s\n' "$expected_checksum" >"${staging_dir}/.release-checksum"
    chmod 0444 "${staging_dir}/.release-checksum"
    mv "$staging_dir" "$release_dir"
    staging_dir=""
fi

active="$(env_value ACTIVE_SLOT)"
if [[ -z "$active" ]]; then
    active="blue"
fi
if [[ "$active" != "blue" && "$active" != "green" ]]; then
    echo "ACTIVE_SLOT must be blue or green" >&2
    exit 78
fi

if [[ "$active" == "blue" ]]; then
    candidate="green"
    candidate_port="18082"
else
    candidate="blue"
    candidate_port="18081"
fi

active_container="warehouse-allocation-api-${active}-1"
if ! docker inspect "$active_container" >/dev/null 2>&1; then
    active_container="warehouse-allocation-api-1"
fi
if ! docker inspect "$active_container" >/dev/null 2>&1; then
    echo "active API container could not be identified" >&2
    exit 69
fi

active_image="$(docker inspect --format '{{.Config.Image}}' "$active_container")"
if [[ "$active" == "blue" ]]; then
    blue_image="$active_image"
    green_image="$candidate_image"
else
    blue_image="$candidate_image"
    green_image="$active_image"
fi

compose config --quiet
docker build \
    --label "ir.mvphub.service=warehouse-allocation" \
    --label "org.opencontainers.image.revision=${release_id}" \
    --tag "$candidate_image" \
    "$release_dir"

compose --profile "$candidate" up -d --no-deps "api-${candidate}"
candidate_started=1

for _attempt in $(seq 1 24); do
    if curl -fsS --max-time 2 "http://127.0.0.1:${candidate_port}/health/ready" \
        >/dev/null; then
        break
    fi
    sleep 2
done
curl -fsS --max-time 5 "http://127.0.0.1:${candidate_port}/health/ready" >/dev/null

docker exec warehouse-allocation-redis-1 \
    redis-cli HSETNX inventory:demo-tehran DEMO-SKU-001 10000 >/dev/null
docker exec warehouse-allocation-redis-1 \
    redis-cli HSETNX inventory:demo-karaj DEMO-SKU-001 10000 >/dev/null

cp -f "$NGINX_UPSTREAM" "$upstream_backup"
write_upstream "$candidate_port"
upstream_changed=1
nginx -t
systemctl reload nginx

curl -fsS --max-time 10 "${PUBLIC_URL}/health/ready" >/dev/null
curl -fsS --max-time 10 "${PUBLIC_URL}/openapi.json" >"$openapi_file"
python3 - "$openapi_file" "$example_file" <<'PY'
import json
import sys

source, destination = sys.argv[1:]
with open(source, encoding="utf-8") as stream:
    document = json.load(stream)
example = document["paths"]["/v1/allocations"]["post"]["requestBody"]["content"][
    "application/json"
]["examples"]["demoQuote"]["value"]
with open(destination, "w", encoding="utf-8") as stream:
    json.dump(example, stream)
PY

for _attempt in 1 2; do
    curl -fsS --max-time 10 \
        -H "Content-Type: application/json" \
        --data-binary "@${example_file}" \
        "${PUBLIC_URL}/v1/allocations" >"$response_file"
    python3 - "$response_file" <<'PY'
import json
import sys

with open(sys.argv[1], encoding="utf-8") as stream:
    response = json.load(stream)
assert response["warehouseId"] in {"demo-tehran", "demo-karaj"}
assert response["inventoryReserved"] is False
assert 0 <= response["routeOptimizationScore"] <= 100
PY
done

previous_release="$(readlink -f "${APP_ROOT}/current" || true)"
upsert_env BLUE_IMAGE "$blue_image"
upsert_env GREEN_IMAGE "$green_image"

new_current="${APP_ROOT}/.current-${release_id}"
ln -s "$release_dir" "$new_current"
mv -Tf "$new_current" "${APP_ROOT}/current"
current_changed=1
upsert_env ACTIVE_SLOT "$candidate"

deployment_complete=1
candidate_started=0
upstream_changed=0

docker rm -f "$active_container" >/dev/null 2>&1 || true
rm -f "$archive"

current_release="$(readlink -f "${APP_ROOT}/current")"
mapfile -t old_releases < <(
    find "$RELEASES_DIR" -mindepth 1 -maxdepth 1 -type d -printf '%T@ %p\n' |
        sort -nr |
        tail -n +6 |
        cut -d ' ' -f 2-
)
for old_release in "${old_releases[@]}"; do
    if [[ "$old_release" != "$current_release" ]]; then
        rm -rf "$old_release"
    fi
done

mapfile -t old_images < <(
    docker image ls "$IMAGE_REPOSITORY" --format '{{.Repository}}:{{.Tag}}' |
        tail -n +6
)
for old_image in "${old_images[@]}"; do
    docker image rm "$old_image" >/dev/null 2>&1 || true
done

rm -rf "$work_dir"
trap - EXIT

echo "warehouse-allocation ${release_id} is active in the ${candidate} slot"
