#!/bin/bash
#
# find_trial_files_size.sh
# Finds "trial-edition" artifact files (e.g. xl-deploy-*-trial-edition.zip)
# and reports their total combined size.
#
# By default, checksum sidecar files (.sha1, .sha512, .md5) are EXCLUDED
# since they aren't real artifact size. Use -a/--all to include them.
#
# Usage:
#   ./find_trial_files_size.sh [search_directory] [-a|--all]
#
# Examples:
#   ./find_trial_files_size.sh /path/to/xl-deploy
#   ./find_trial_files_size.sh /path/to/xl-deploy --all

set -euo pipefail

SEARCH_DIR="."
INCLUDE_CHECKSUMS=0

# Parse args (order-independent)
for arg in "$@"; do
    case "$arg" in
        -a|--all)
            INCLUDE_CHECKSUMS=1
            ;;
        *)
            SEARCH_DIR="$arg"
            ;;
    esac
done

if [ ! -d "$SEARCH_DIR" ]; then
    echo "Error: '$SEARCH_DIR' is not a valid directory." >&2
    exit 1
fi

echo "Searching for trial-edition files in: $SEARCH_DIR"
[ "$INCLUDE_CHECKSUMS" -eq 1 ] && echo "(including checksum sidecar files)"
echo "----------------------------------------------------------"

if [ "$INCLUDE_CHECKSUMS" -eq 1 ]; then
    mapfile -t FILES < <(find "$SEARCH_DIR" -type f -iname "*trial-edition*" 2>/dev/null | sort)
else
    mapfile -t FILES < <(find "$SEARCH_DIR" -type f -iname "*trial-edition*" \
        ! -iname "*.sha1" ! -iname "*.sha512" ! -iname "*.md5" 2>/dev/null | sort)
fi

if [ "${#FILES[@]}" -eq 0 ]; then
    echo "No matching files found."
    exit 0
fi

TOTAL_BYTES=0
for f in "${FILES[@]}"; do
    SIZE=$(stat -c%s "$f" 2>/dev/null || stat -f%z "$f")
    HUMAN_SIZE=$(du -h "$f" | cut -f1)
    printf "%-10s %s\n" "$HUMAN_SIZE" "$f"
    TOTAL_BYTES=$((TOTAL_BYTES + SIZE))
done

echo "----------------------------------------------------------"
echo "Total files found: ${#FILES[@]}"

TOTAL_HUMAN=$(numfmt --to=iec --suffix=B "$TOTAL_BYTES" 2>/dev/null || echo "${TOTAL_BYTES} bytes")
echo "Total combined size: $TOTAL_HUMAN"
