#!/usr/bin/env bash
#
# export-changes.sh [n]
#   n = number of days to look back (default: 0 = today only)
#
# Creates a zip with all files modified in the last n days,
# preserving the folder structure relative to the repo root.

set -euo pipefail

DAYS="${1:-0}"
REPO_ROOT="$(git rev-parse --show-toplevel)"
cd "$REPO_ROOT"

SINCE_DATE="$(date -d "$DAYS days ago" +%Y-%m-%d 2>/dev/null || date -v-"${DAYS}"d +%Y-%m-%d)"
TIMESTAMP="$(date +%Y%m%d_%H%M%S)"
ZIPNAME="update_${TIMESTAMP}_${DAYS}d.zip"

# Collect existing files modified since the date
FILELIST=$(git log --since="$SINCE_DATE" --name-only --pretty=format: | sort -u | grep -v '^$' || true)

if [ -z "$FILELIST" ]; then
    echo "No files modified in the last $DAYS day(s)."
    exit 0
fi

# Filter to only existing files and build the zip
COUNT=0
TMPLIST=$(mktemp)
while IFS= read -r f; do
    if [ -f "$f" ]; then
        echo "$f" >> "$TMPLIST"
        COUNT=$((COUNT + 1))
    fi
done <<< "$FILELIST"

if [ "$COUNT" -eq 0 ]; then
    echo "No existing files found among the modified ones."
    rm -f "$TMPLIST"
    exit 0
fi

# Try zip first, fall back to tar+gzip
if command -v zip &>/dev/null; then
    cat "$TMPLIST" | xargs zip -r "$ZIPNAME"
elif command -v 7z &>/dev/null; then
    7z a "$ZIPNAME" "@$TMPLIST"
else
    ZIPNAME="update_${TIMESTAMP}_${DAYS}d.tar.gz"
    tar czf "$ZIPNAME" -T "$TMPLIST"
fi

rm -f "$TMPLIST"
echo ""
echo "Created: $ZIPNAME ($COUNT files, $(du -h "$ZIPNAME" | cut -f1))"
