#!/usr/bin/env bash

set -euo pipefail

site_root=${COVERAGE_SITE_ROOT:-/workspace/public}
raw_root="${site_root}/raw"
reports_root="${site_root}/storage/reports"

: "${MINIO_BUCKET:?MINIO_BUCKET is required}"
: "${COVERAGE_OBJECT_PREFIX:?COVERAGE_OBJECT_PREFIX is required}"
: "${MINIO_ENDPOINT:?MINIO_ENDPOINT is required}"
: "${MINIO_ACCESS_KEY_ID:?MINIO_ACCESS_KEY_ID is required}"
: "${MINIO_SECRET_ACCESS_KEY:?MINIO_SECRET_ACCESS_KEY is required}"

site_title=${COVERAGE_SITE_TITLE:-Cloud Storage Engine Coverage History}

bucket=${MINIO_BUCKET}
object_prefix=${COVERAGE_OBJECT_PREFIX}

mkdir -p "${raw_root}" "${reports_root}" "${site_root}/latest"

export AWS_ACCESS_KEY_ID="${MINIO_ACCESS_KEY_ID}"
export AWS_SECRET_ACCESS_KEY="${MINIO_SECRET_ACCESS_KEY}"
export AWS_DEFAULT_REGION="${AWS_DEFAULT_REGION:-us-east-1}"
export AWS_EC2_METADATA_DISABLED="${AWS_EC2_METADATA_DISABLED:-true}"

source_path="s3://${bucket}"
if [[ -n "${object_prefix}" ]]; then
    source_path="${source_path}/${object_prefix%/}"
fi

tmp_dir=$(mktemp -d)
trap 'rm -rf "${tmp_dir}"' EXIT

echo "Syncing manifests from MinIO..."
aws s3 sync \
    "${source_path}" \
    "${tmp_dir}" \
    --endpoint-url "${MINIO_ENDPOINT}" \
    --only-show-errors \
    --exclude "*" \
    --include "*.manifest.json"

cutoff_epoch=$(date -d "45 days ago" +%s)

is_manifest_too_old() {
    local manifest_path=$1
    local generated_at
    generated_at=$(jq -r '.generated_at // empty' "${manifest_path}")
    if [[ -z "${generated_at}" ]]; then
        return 0
    fi
    # Convert %Y%m%dT%H%M%SZ -> %Y-%m-%dT%H:%M:%SZ for date(1)
    local formatted_at
    formatted_at=$(printf '%s' "${generated_at}" | sed 's/\(....\)\(..\)\(..\)T\(..\)\(..\)\(..\)Z/\1-\2-\3T\4:\5:\6Z/')
    local manifest_epoch
    manifest_epoch=$(date -d "${formatted_at}" +%s 2>/dev/null || echo 0)
    if [[ "${manifest_epoch}" -lt "${cutoff_epoch}" ]]; then
        return 0
    fi
    return 1
}

extract_report() {
    local short_sha=$1
    local tarball_name="${short_sha}.tar.gz"
    local report_dir="${reports_root}/${short_sha}"

    echo "Downloading tarball: ${tarball_name}"
    if ! aws s3 cp "${source_path}/${tarball_name}" "${raw_root}/${tarball_name}" \
        --endpoint-url "${MINIO_ENDPOINT}" --only-show-errors; then
        echo "Warning: failed to download tarball ${tarball_name}" >&2
        return 1
    fi

    echo "Extracting report: ${short_sha}"
    local tmp_report_dir="${report_dir}.tmp.$$"
    rm -rf -- "${tmp_report_dir}"
    mkdir -p "${tmp_report_dir}"
    if ! tar -xzf "${raw_root}/${tarball_name}" -C "${tmp_report_dir}"; then
        rm -rf -- "${tmp_report_dir}"
        return 1
    fi

    local old_report_dir="${report_dir}.old.$$"
    if [[ -d "${report_dir}" ]]; then
        mv "${report_dir}" "${old_report_dir}"
    fi
    mv "${tmp_report_dir}" "${report_dir}"
    if [[ -d "${old_report_dir}" ]]; then
        rm -rf -- "${old_report_dir}"
    fi

    chmod -R a+rX "${report_dir}"
}

while IFS= read -r -d '' tmp_manifest; do
    rel_path="${tmp_manifest#${tmp_dir}/}"
    local_manifest="${raw_root}/${rel_path}"

    if is_manifest_too_old "${tmp_manifest}"; then
        echo "Skipping manifest older than 45 days: ${rel_path}"
        continue
    fi

    short_sha=$(jq -r '.short_sha // (.sha // empty | .[:12])' "${tmp_manifest}" | tr -cd '[:alnum:]')

    if [[ -z "${short_sha}" ]]; then
        echo "Warning: cannot determine short_sha for ${rel_path}, skipping" >&2
        continue
    fi

    report_dir="${reports_root}/${short_sha}"

    manifest_changed=0
    if [[ ! -f "${local_manifest}" ]]; then
        echo "New manifest: ${rel_path}"
        manifest_changed=1
    elif ! cmp -s "${tmp_manifest}" "${local_manifest}"; then
        echo "Updated manifest: ${rel_path}"
        manifest_changed=1
    elif [[ ! -d "${report_dir}" ]]; then
        echo "Missing report for manifest: ${rel_path}"
        manifest_changed=1
    fi

    if [[ "${manifest_changed}" -eq 0 ]]; then
        continue
    fi

    if extract_report "${short_sha}"; then
        mkdir -p "$(dirname "${local_manifest}")"
        cp "${tmp_manifest}" "${local_manifest}"
    else
        echo "Warning: Failed to extract report for ${short_sha}, skipping" >&2
    fi
done < <(find "${tmp_dir}" -name "*.manifest.json" -print0)

while IFS= read -r -d '' local_manifest; do
    rel_path="${local_manifest#${raw_root}/}"

    if is_manifest_too_old "${local_manifest}"; then
        echo "Removing local manifest older than 45 days: ${rel_path}"
        short_sha=$(jq -r '.short_sha // (.sha // empty | .[:12])' "${local_manifest}" 2>/dev/null | tr -cd '[:alnum:]' || true)
        rm -f "${local_manifest}"
        if [[ -n "${short_sha}" ]]; then
            rm -rf -- "${reports_root}/${short_sha}"
            rm -f "${raw_root}/${short_sha}.tar.gz"
        fi
        continue
    fi

    if [[ ! -f "${tmp_dir}/${rel_path}" ]]; then
        echo "Removing deleted manifest: ${rel_path}"

        short_sha=$(jq -r '.short_sha // (.sha // empty | .[:12])' "${local_manifest}" 2>/dev/null | tr -cd '[:alnum:]' || true)

        rm -f "${local_manifest}"

        if [[ -n "${short_sha}" ]]; then
            rm -rf -- "${reports_root}/${short_sha}"
            rm -f "${raw_root}/${short_sha}.tar.gz"
        fi
    fi
done < <(find "${raw_root}" -name "*.manifest.json" -print0)

python3 /workspace/generate_index.py \
    --site-root "${site_root}" \
    --manifest-root "${raw_root}" \
    --report-base-path "/storage/reports" \
    --site-title "${site_title}"

chmod -R a+rX "${site_root}"
