#!/usr/bin/env bash
# Publishes a theme's screenshots to https://theme-screenshots.space.fast/<slug>/
# and adds the theme to the list on the front page.
#
#   bash .theme-utils/screenshots/publish.sh <theme-slug> <shots-dir> [note]
#
# Needs SPACEFAST_TOKEN (CI) or a logged-in Spacefast CLI. With PR_NUMBER set,
# the gallery links to the workflow's Run workflow page to take new screenshots. The space keeps the
# 11 most recently updated themes. Each publish replaces the whole site: this
# theme's new gallery plus copies of the other kept galleries, taken from the
# live site. Spacefast's CLI can't delete single files, so this is how the
# oldest gallery goes away.
set -euo pipefail

SLUG="${1:?theme slug}"
SHOTS="${2:?screenshots folder}"
NOTE="${3:-}"
HERE="$(cd "$(dirname "$0")" && pwd)"
REPO="$(cd "$HERE/../.." && pwd)"
SPACE="spc_797fb54deff8421488a0233013b2d7a6"
SITE_URL="https://theme-screenshots.space.fast"
KEEP=11

[[ "$SLUG" =~ ^[A-Za-z0-9_-]+$ ]] || { echo "Bad theme slug: $SLUG"; exit 1; }
NAME=$(sed -n 's/^[[:space:]]*Theme Name:[[:space:]]*//p' "$REPO/$SLUG/style.css" | head -1 | tr -d '\r' | xargs)
NAME="${NAME:-$SLUG}"

SITE="$(mktemp -d)"
trap 'rm -rf "$SITE"' EXIT
mkdir -p "$SITE/$SLUG"
# Copy only the images and the shot list; the gallery page is built here.
cp "$SHOTS"/*.webp "$SHOTS"/*.png "$SHOTS/shots.json" "$SITE/$SLUG/" 2> /dev/null || true
[ -f "$SITE/$SLUG/shots.json" ] || { echo "No shots.json in $SHOTS"; exit 1; }
node "$HERE/gallery.cjs" theme "$SITE/$SLUG" "$NAME" "$NOTE"

# The theme's own screenshot.png or .jpg, 600px wide, for the list of themes.
COVER=""
for SRC in "$REPO/$SLUG/screenshot.png" "$REPO/$SLUG/screenshot.jpg"; do
	[ -f "$SRC" ] || continue
	node -e '
		const sharp = require( process.env.SHARP_PATH || "sharp" );
		sharp( process.argv[ 1 ] ).resize( 600 ).webp( { quality: 82 } ).toFile( process.argv[ 2 ] ).catch( ( e ) => { console.error( e ); process.exit( 1 ); } );
	' "$SRC" "$SITE/$SLUG/cover.webp" && COVER="cover.webp"
	break
done

# Put this theme first in the list of themes and keep the newest $KEEP.
curl -sf "$SITE_URL/themes.json" -o "$SITE/old.json" || echo '[]' > "$SITE/old.json"
node -e '
	const fs = require( "fs" );
	const [ file, slug, name, keep, outFile, cover ] = process.argv.slice( 1 );
	const list = JSON.parse( fs.readFileSync( file, "utf8" ) )
		.filter( ( t ) => t.slug !== slug && /^[A-Za-z0-9_-]+$/.test( t.slug ) )
		.sort( ( a, b ) => String( b.updated ).localeCompare( String( a.updated ) ) );
	list.unshift( { slug, name, updated: new Date().toISOString(), ...( cover && { cover } ) } );
	fs.writeFileSync( outFile, JSON.stringify( list.slice( 0, Number( keep ) ), null, "\t" ) );
	list.slice( Number( keep ) ).forEach( ( t ) => console.log( `Removing ${ t.slug }: older than the newest ${ keep }` ) );
' "$SITE/old.json" "$SLUG" "$NAME" "$KEEP" "$SITE/themes.json" "$COVER"
rm "$SITE/old.json"

# Copy the other kept galleries from the live site: the page and every image it
# links to. Stop if any file is missing, so a failed download never drops a theme.
for OTHER in $(node -e 'JSON.parse( require( "fs" ).readFileSync( process.argv[ 1 ], "utf8" ) ).forEach( ( t ) => console.log( t.slug ) )' "$SITE/themes.json"); do
	[ "$OTHER" = "$SLUG" ] && continue
	mkdir -p "$SITE/$OTHER"
	curl -sf "$SITE_URL/$OTHER/" -o "$SITE/$OTHER/index.html"
	curl -sf "$SITE_URL/$OTHER/shots.json" -o "$SITE/$OTHER/shots.json" || rm -f "$SITE/$OTHER/shots.json"
	for FILE in $(grep -o 'href="[A-Za-z0-9_-]*\.\(webp\|png\)"' "$SITE/$OTHER/index.html" | cut -d'"' -f2 | sort -u); do
		curl -sf "$SITE_URL/$OTHER/$FILE" -o "$SITE/$OTHER/$FILE"
	done
	OTHER_COVER=$(node -e 'const t = JSON.parse( require( "fs" ).readFileSync( process.argv[ 1 ], "utf8" ) ).find( ( t ) => t.slug === process.argv[ 2 ] ); console.log( /^[A-Za-z0-9_-]+\.webp$/.test( t.cover || "" ) ? t.cover : "" )' "$SITE/themes.json" "$OTHER")
	[ -z "$OTHER_COVER" ] || curl -sf "$SITE_URL/$OTHER/$OTHER_COVER" -o "$SITE/$OTHER/$OTHER_COVER"
	echo "Kept $OTHER"
done
node "$HERE/gallery.cjs" list "$SITE" "$SITE/themes.json"

# Run npx outside the repo (see capture.sh). The version is pinned: 0.8.0
# shipped depending on a package that wasn't on npm and broke the publish.
cd "$SITE/.."
npx -y spacefast@0.5.0 publish "$SITE" --space "$SPACE" --publish-mode snapshot \
	--message "$NAME screenshots" --wait --json -y > "$SITE.publish.json" ||
	{ cat "$SITE.publish.json"; exit 1; }
rm -f "$SITE.publish.json"
echo "Published $SITE_URL/$SLUG/"
