#!/usr/bin/env bash
set -euo pipefail

root="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
chrome="${CHROME_BIN:-/usr/bin/google-chrome}"

capture() {
	local width="$1"
	local height="$2"
	local output="$3"
	local query="$4"
	local raw
	local profile
	raw="$(mktemp --suffix=.png)"
	profile="$(mktemp -d)"
	mkdir -p "$(dirname "$root/$output")"
	"$chrome" \
		--headless=new \
		--disable-gpu \
		--hide-scrollbars \
		--run-all-compositor-stages-before-draw \
		--virtual-time-budget=1000 \
		--force-device-scale-factor=1 \
		--user-data-dir="$profile" \
		--window-size="$width,$((height + 87))" \
		--screenshot="$raw" \
		"file://$root/render.html?$query"
	ffmpeg -v error -y -i "$raw" \
		-vf "crop=$width:$height:0:0" \
		-frames:v 1 \
		"$root/$output"
	unlink "$raw"
	find "$profile" -depth -delete
}

for locale in en-US it-IT; do
	for slide in 1 2 3; do
		case "$slide" in
			1) state="idle" ;;
			2) state="connecting" ;;
			3) state="connected" ;;
		esac

		capture 1284 2778 \
			"app-store/$locale/iphone-6.5/0${slide}-${state}.png" \
			"platform=app-store&locale=$locale&slide=$slide&shot=source/ios/$locale/$state.png"
		capture 1080 1920 \
			"google-play/$locale/phone/0${slide}-${state}.png" \
			"platform=google&locale=$locale&slide=$slide&shot=source/android/$locale/$state.png"
	done

	capture 1024 500 \
		"google-play/$locale/feature-graphic.png" \
		"platform=feature&locale=$locale"
done
