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

script_source="${BASH_SOURCE[0]:-$0}"
while [[ -L "$script_source" ]]; do
    script_dir="$(cd "$(dirname "$script_source")" && pwd -P)"
    script_source="$(readlink "$script_source")"
    [[ "$script_source" != /* ]] && script_source="$script_dir/$script_source"
done
script_dir="$(cd "$(dirname "$script_source")" && pwd -P)"
repo_dir="$(cd "$script_dir/.." && pwd -P)"
rust_bin="$repo_dir/target/debug/constant"
cache_root="${XDG_CACHE_HOME:-$HOME/.cache}/constant/wrapper"

record_wrapper_mode() {
    local reason="$1"
    mkdir -p "$cache_root"
    printf '%s %s %s\n' "rust" "$reason" "$(date +%s)" > "$cache_root/last-mode"
    export CONSTANT_WRAPPER_LAST_REASON="$reason"
}

sign_binary_if_possible() {
    command -v codesign >/dev/null 2>&1 || return 0
    codesign --force -s - "$rust_bin" >/dev/null 2>&1 || true
}

needs_build() {
    [[ -x "$rust_bin" ]] || return 0
    [[ "$repo_dir/Cargo.toml" -nt "$rust_bin" ]] && return 0
    [[ -f "$repo_dir/Cargo.lock" && "$repo_dir/Cargo.lock" -nt "$rust_bin" ]] && return 0
    if find "$repo_dir/src" "$repo_dir/tests" -type f -newer "$rust_bin" -print -quit 2>/dev/null | grep -q .; then
        return 0
    fi
    return 1
}

if needs_build; then
    cargo build --manifest-path "$repo_dir/Cargo.toml" --quiet
    sign_binary_if_possible
    record_wrapper_mode "rebuilt"
else
    record_wrapper_mode "reused-binary"
fi

export CONSTANT_PROG_NAME="${CONSTANT_PROG_NAME:-$(basename "$0")}"
export CONSTANT_REPO_DIR="$repo_dir"
exec "$rust_bin" "$@"
