#!/usr/bin/env bash

set -euo pipefail

DIR="${1:-.}"

cd "$DIR"

for f in *; do
    # Skip if not a regular file
    [[ -f "$f" ]] || continue

    # URL-decode the filename
    decoded=$(printf '%b' "${f//%/\\x}")

    # Skip if name is unchanged
    if [[ "$f" == "$decoded" ]]; then
        continue
    fi

    # Prevent overwriting existing files
    if [[ -e "$decoded" ]]; then
        echo "Skipping (target exists): $f -> $decoded"
        continue
    fi

    echo "Renaming: $f -> $decoded"
    mv -- "$f" "$decoded"
done

