#!/usr/bin/env bash
#
# client_report.sh - Generate a CSV report of Perforce client workspaces for maintenance review.

usage() {
    cat <<EOF
Usage: $(basename "$0") [-h] [OUTPUT_FILE]

Generate a CSV report of all Perforce client workspaces, including last access date,
owner, and ready-to-run commands for unloading, reloading, or deleting each client.

Useful for identifying stale workspaces and performing bulk cleanup operations.

Arguments:
  OUTPUT_FILE   Path for the output CSV file (default: client_report.csv)

Options:
  -h            Show this help message and exit

Examples:
  $(basename "$0")
  $(basename "$0") /tmp/p4_clients_$(date +%Y%m%d).csv

Requirements:
  - p4 CLI must be in PATH and authenticated
  - 'date' must support the -d flag (GNU coreutils)
EOF
}

# --- Argument parsing ---

while getopts ":h" opt; do
    case $opt in
        h) usage; exit 0 ;;
        \?) echo "Unknown option: -$OPTARG" >&2; usage >&2; exit 1 ;;
    esac
done
shift $((OPTIND - 1))

OUTPUT="${1:-client_report.csv}"

# --- Main ---

echo "Client, Last Access, Owner, Command to unload client, Command to reload client, Command to remove client" > "$OUTPUT"

p4 -ztag -F "%client%|%Access%|%Owner%" clients | while IFS='|' read -r client access owner; do
    if [[ -z "$access" || "$access" == "0" ]]; then
        formatted="N/A"
    else
        formatted=$(date -d "@$access" +"%m/%d/%Y")
    fi
    echo "$client, $formatted, $owner, p4 unload -c $client, p4 reload -c $client, p4 client -d $client"
done >> "$OUTPUT"

echo "Report written to: $OUTPUT"
