#!/bin/bash

# Ensure ~/.local/bin is on PATH
export PATH=$PATH:$HOME/.local/bin

PATCH_VIA_GERRIT=~/.local/bin/patch_via_gerrit

install_patch_via_gerrit() {
    # Use uv to install/upgrade patch_via_gerrit
    uv tool install --python-preference=only-managed --reinstall --quiet patch_via_gerrit
}

# If patch_via_gerrit isn't already installed, ensure uv is installed and then use
# it to install patch_via_gerrit
if [ ! -x ${PATCH_VIA_GERRIT} ]; then

    # If uv isn't already installed, install it - use curl or wget
    if ! command -v uv 2>&1 >/dev/null; then
        if command -v curl 2>&1 >/dev/null; then
            curl -qLsSf https://astral.sh/uv/install.sh | INSTALLER_PRINT_QUIET=1 sh
        elif command -v wget 2>&1 >/dev/null; then
            wget -qO- https://astral.sh/uv/install.sh | INSTALLER_PRINT_QUIET=1 sh
        else
            echo "Either curl or wget is required to install patch_via_gerrit"
            exit 1
        fi
    fi

    install_patch_via_gerrit

else

    # If patch_via_gerrit is installed but more than a couple days old, update it
    if [[ $(find ${PATCH_VIA_GERRIT} -mtime +2 -print) ]]; then
        install_patch_via_gerrit
    fi

fi

# Invoke patch_via_gerrit
exec ~/.local/bin/patch_via_gerrit "$@"
