#!/bin/bash

set -e

W=1280
H=720

A=${1}
B=${2}
MATTE=${3}
OUTPUT=${4}

MATTE1=matte1.mov
MATTE2=matte2.mov
PASS1=pass1.mov
PASS2=pass2.mov

echo "Generating mattes from $MATTE..."

ffmpeg -y -i "$MATTE"  -vf eq=saturation=0:contrast=100,smartblur=1 -c:v prores_ks -profile:v 4 "$MATTE1" 
ffmpeg -y -i "$MATTE1" -vf negate -c:v prores_ks -profile:v 4 "$MATTE2"

echo "Applying matte to $A..."

ffmpeg -y -i "$A" -i "$MATTE1" \
	-filter_complex 'color=0x000000:size=1280x720,format=rgb24[bla];[bla][0][1]maskedmerge' \
	-c:v prores_ks \
	-profile:v 4 \
	-shortest \
	"$PASS1"

echo "Applying matte to $B..."

ffmpeg -y -i "$B" -i "$MATTE2" \
	-filter_complex 'color=0x000000:size=1280x720,format=rgb24[bla];[bla][0][1]maskedmerge' \
	-c:v prores_ks \
	-profile:v 4 \
	-shortest \
	"$PASS2"

echo "Cleaning up tmp matte files..."

rm "$MATTE1"
rm "$MATTE2"

echo "Combining matted layers together into $OUTPUT_FILE..."

ffmpeg -y -i "$PASS1" -i "$PASS2" \
	-filter_complex "[0][1]blend=all_mode='lighten'" \
	-c:v prores_ks \
	-profile:v 3 \
	-shortest \
	"$OUTPUT"

echo "Cleaning up temp files..."

rm "$PASS1"
rm "$PASS2"