IFS=$'\n'

# Initialize an empty string to hold the list of books in JSON-like format
books=""
filecount=$(find /home/naomi/cloud/Books -type f | wc -l)
echo "Found $filecount files."
current=0

# Loop over each file found by find
for file in $(find /home/naomi/cloud/Books -type f -print0 | tr '\0' '\n'); do
    current=$((current + 1))
    echo -ne "Processing $current/$filecount\r"
    title=$(exiftool "$file" | grep "^Title\s*:" | cut -d ":" -f 2 | sed -e 's/^[[:space:]]*//')
    author=$(exiftool "$file" | grep "^Creator\s*:" | cut -d ":" -f 2 | sed -e 's/^[[:space:]]*//')

    if [ -z "$title" ]; then
        # remove .mp3 from the title
        title=$(basename "$file" | sed -e 's/\.*//g')
    fi
    if [ -z "$author" ]; then
        author=$(exiftool "$file" | grep "^Author\s*:" | cut -d ":" -f 2 | sed -e 's/^[[:space:]]*//')
    fi
    if [ -z "$author" ]; then
        author="Unknown Author"
    fi

    # use jq to add the book to the list
    books="$books$(jq -n --arg title "$title" --arg author "$author" '{title: $title, author: $author}'),"
done

# Remove trailing comma and add square brackets to complete the list
books="[${books%,}]"

# Write to ./books/books.json
echo "$books" > ./books/books.json
echo -ne "Done!\r"