#!/usr/bin/env bash
#
# label_report.sh - Generate a CSV report of Perforce labels for maintenance review.

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

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

Useful for identifying stale labels and performing bulk cleanup operations.

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

Options:
  -h            Show this help message and exit

Examples:
  $(basename "$0")
  $(basename "$0") /tmp/p4_labels_$(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:-label_report.csv}"

# --- Main ---

echo "Label, Last Access, Owner, Command to unload label, Command to reload label, Command to remove label" > "$OUTPUT"

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

echo "Report written to: $OUTPUT"
