#! /usr/bin/env nix-shell
#! nix-shell -i bash -p bash fd

SOURCE_DIR="/srv/pool/scrapping/JawZ/gallery-dl/"
OUTPUT_DIR="/var/www/gallery"
PREVIEW_COUNT=24

mkdir -p "$OUTPUT_DIR"
cd "$SOURCE_DIR" || exit 1

while IFS= read -r dir; do
    artist_name="${dir%/}"
    artist_output="$OUTPUT_DIR/$artist_name"
    mkdir -p "$artist_output/.preview"

    # Clean any previous preview
    rm -rf "$artist_output/.preview"/*
    fd . "$dir" --maxdepth 1 -tf -e jpg -e jpeg -e png |
        shuf -n "$PREVIEW_COUNT" |
        while read -r img; do
            cp "$img" "$artist_output/.preview/"
        done

    # Generate index.html for the artist
    {
        echo "<html><head><title>$artist_name</title>"
        echo "<style>body{font-family:sans-serif} img{max-width:200px; margin:5px;}</style></head><body>"
        echo "<h2>$artist_name</h2><div>"
        for img in "$artist_output/.preview/"*; do
            img_name="$(basename "$img")"
            echo "<img src=\".preview/$img_name\" loading=\"lazy\">"
        done
        echo "</div><p><a href=\"../index.html\">Back to index</a></p></body></html>"
    } >"$artist_output/index.html"
done < <(fd . -td)

# Generate master index.html
{
    echo "<html><head><title>Gallery Index</title></head><body><h1>Gallery Index</h1><ul>"
    for dir in "$OUTPUT_DIR"/*/; do
        artist="$(basename "$dir")"
        echo "<li><a href=\"./$artist/index.html\">$artist</a></li>"
    done
    echo "</ul></body></html>"
} >"$OUTPUT_DIR/index.html"
