#!/bin/bash
set -euo pipefail

usage() {
    echo "Usage: cpw [OPTIONS] SOURCE... DESTINATION"
    echo "Copy files using 'wich' to resolve paths, with cp options support."
    echo
    echo "Options:"
    echo "  -h, --help    Display this help message and exit"
    echo "  Any other options supported by 'cp' command"
}

if [[ $# -eq 0 || "$1" == "-h" || "$1" == "--help" ]]; then
    usage
    exit 0
fi

# Store all arguments
args=("$@")

# Pop the last argument as the target
target=${args[-1]} ; unset 'args[-1]'

# Initialize arrays for options and files
options=() files=()

# Process arguments
for arg in "${args[@]}"; do
    if [[ $arg == -* ]]; then
        options+=("$arg")
    else
        path=$(wich "$arg")
        if [ -z "$path" ]; then
            echo >&2 "Not found: $arg"
            exit 1
        fi
        files+=("$path")
    fi
done

# Execute cp command
cp "${options[@]}" "${files[@]}" "$target"
