#!/bin/bash
# Remove one user's legacy uv tool without privileged filesystem access.

set -u

user_home="${1:?missing home}"
expected_uid="${2:?missing uid}"
actual_uid=$(/usr/bin/id -u) || exit 0
[ "$actual_uid" = "$expected_uid" ] || exit 0

resolve_symlink_target() {
    local path="$1"
    local link=""
    local directory=""
    local filename=""
    local physical_directory=""
    local hops=0

    while [ -L "$path" ]; do
        [ "$hops" -lt 40 ] || return 1
        link=$(/usr/bin/readlink "$path" 2>/dev/null) || return 1
        case "$link" in
            /*) path="$link" ;;
            *) path="$(/usr/bin/dirname "$path")/$link" ;;
        esac
        hops=$((hops + 1))
    done

    directory=$(/usr/bin/dirname "$path")
    filename=$(/usr/bin/basename "$path")
    physical_directory=$(cd -P "$directory" 2>/dev/null && /bin/pwd -P) ||
        return 1
    printf '%s/%s\n' "$physical_directory" "$filename"
}

path_has_symlink() {
    local current="$1"
    shift
    local part=""

    for part in "$@"; do
        current="$current/$part"
        [ -L "$current" ] && return 0
    done
    return 1
}

path_owner_uid() {
    /usr/bin/stat -f '%u' "$1" 2>/dev/null
}

shim="$user_home/.local/bin/runlayer"
resolved_target=""
tool_dir=""

if [ -L "$shim" ]; then
    resolved_target=$(resolve_symlink_target "$shim") || resolved_target=""
    case "$resolved_target" in
        /*/uv/tools/runlayer/*)
            tool_dir="${resolved_target%%/uv/tools/runlayer/*}/uv/tools/runlayer"
            ;;
        /*/uv/tools/runlayer)
            tool_dir="$resolved_target"
            ;;
    esac
fi

if [ -n "$tool_dir" ] &&
    [ -d "$tool_dir" ] &&
    [ ! -L "$tool_dir" ] &&
    [ "$(path_owner_uid "$tool_dir")" = "$expected_uid" ]; then
    rm -rf "$tool_dir" 2>/dev/null || true
    if ! path_has_symlink "$user_home" .local bin &&
        [ -L "$shim" ] &&
        [ "$(path_owner_uid "$shim")" = "$expected_uid" ]; then
        rm -f "$shim" 2>/dev/null || true
    fi
fi

default_tool_dir="$user_home/.local/share/uv/tools/runlayer"
if ! path_has_symlink "$user_home" .local share uv tools runlayer &&
    [ -d "$default_tool_dir" ] &&
    [ ! -L "$default_tool_dir" ] &&
    [ "$(path_owner_uid "$default_tool_dir")" = "$expected_uid" ]; then
    rm -rf "$default_tool_dir" 2>/dev/null || true
fi

exit 0
