#!/bin/bash
# Usage: rename [--dry-run] [--verbose] 'sed_pattern' files...

show_help() {
  echo "Usage: $(basename "$0") [--dry-run] [--verbose] 'sed_pattern' files..."
  echo "Example: $(basename "$0") 's/txt$/md/' *.txt"
  exit 0
}

dry_run=0
verbose=0

# Parse options
while [[ $1 == --* ]]; do
  case "$1" in
  --help | -h)
    show_help
    ;;
  --dry-run)
    dry_run=1
    shift
    ;;
  --verbose)
    verbose=1
    shift
    ;;
  *)
    echo "Unknown option: $1"
    show_help
    ;;
  esac
done

if [ "$#" -lt 2 ]; then
  show_help
fi

pattern="$1"
shift

for file in "$@"; do
  newname=$(echo "$file" | sed "$pattern")
  if [ "$file" != "$newname" ]; then
    cmd="mv \"$file\" \"$newname\""
    if [ $dry_run -eq 1 ]; then
      echo "$cmd"
    elif [ $verbose -eq 1 ]; then
      echo "$cmd"
      eval "$cmd"
    else
      eval "$cmd"
    fi
  fi
done
