#!/bin/bash

# Get absolute path of script directory
SCRIPT_DIR=$(dirname "$(readlink -f "$0")")
RSS_DIR="$SCRIPT_DIR/../rss"
RSS_FILE="$RSS_DIR/sweet_liberty.xml"
TMP_DIR="$SCRIPT_DIR/tmp_rss_items"

# Ensure directories exist
mkdir -p "$RSS_DIR"
mkdir -p "$TMP_DIR"
rm -f "$TMP_DIR"/*

# Loop through MP3s safely
for f in "$SCRIPT_DIR"/*.mp3; do
    # Get just filename
    fname=$(basename "$f")
    title="${fname%.mp3}"
    url="https://archive.seleniteplus.com/Sweet_Liberty/audio/$fname"
    size=$(stat -c%s "$f")

    # Default timestamp and pubdate
    timestamp=0
    pubdate="Sat, 01 Jan 2000 00:00:00 -0500"

    # Attempt numeric date extraction (MMDDYY or MMDDYYYY)
    base="$title"
    if [[ $base =~ ^([0-1][0-9])([0-3][0-9])([0-9]{2,4})$ ]]; then
        month=${BASH_REMATCH[1]}
        day=${BASH_REMATCH[2]}
        year=${BASH_REMATCH[3]}
        # Convert 2-digit year
        if [ ${#year} -eq 2 ]; then
            if [ "$year" -ge 50 ]; then
                year="19$year"
            else
                year="20$year"
            fi
        fi
        pubdate=$(date -d "$year-$month-$day" +"%a, %d %b %Y 00:00:00 -0500")
        timestamp=$(date -d "$year-$month-$day" +"%s")
    fi

    # Save item to temp file safely
    tmpfile="$TMP_DIR/$timestamp-$(echo "$fname" | tr ' ' '_').item"
    cat > "$tmpfile" <<EOL
<item>
<title>$title</title>
<enclosure url="$url" length="$size" type="audio/mpeg"/>
<guid>$url</guid>
<pubDate>$pubdate</pubDate>
</item>
EOL
done

# Start RSS feed
cat > "$RSS_FILE" <<EOL
<?xml version="1.0" encoding="utf-8"?>
<rss version="2.0" xmlns:itunes="http://www.itunes.com/dtds/podcast-1.0.dtd" xmlns:atom="http://www.w3.org/2005/Atom">
<channel>
<title>Sweet Liberty Archive</title>
<link>https://archive.seleniteplus.com</link>
<description>All Alan Watt Sweet Liberty audio.</description>
<language>en-us</language>
<itunes:author>Alan Watt</itunes:author>
<itunes:explicit>no</itunes:explicit>
<itunes:image href="https://archive.seleniteplus.com/logo.jpg"/>
<ttl>120</ttl>
EOL

# Append items sorted by timestamp descending
for item in $(ls -1 "$TMP_DIR" | sort -r); do
    cat "$TMP_DIR/$item" >> "$RSS_FILE"
done

# Close RSS
cat >> "$RSS_FILE" <<EOL
</channel>
</rss>
EOL

# Clean up temp
rm -rf "$TMP_DIR"

echo "✅ RSS feed successfully generated at: $RSS_FILE"
