#!/bin/sh
# Edit and export a short video with the installed openshot-cli in a headless
# session: exercises openshot-qt, python3-openshot and libopenshot together.
set -eu

cd "$AUTOPKGTEST_TMP"
export HOME="$AUTOPKGTEST_TMP/home" QT_QPA_PLATFORM=offscreen
mkdir -p "$HOME"

json() {
	python3 -c 'import json, sys
d = json.load(sys.stdin)
assert d["ok"], d
for key in sys.argv[1:]:
    d = d[key]
print(d)' "$@"
}

OPENSHOT_SESSION=$(openshot-cli session start | json result session_id)
export OPENSHOT_SESSION
trap 'openshot-cli session stop --discard >/dev/null 2>&1 || true' EXIT

image=/usr/lib/python3/dist-packages/openshot_qt/images/mask.png
file_id=$(openshot-cli file import "$image" | json result data id)
openshot-cli clip add --layer 1000000 --end 2 "$file_id" | json result data id
openshot-cli --timeout 300 export start "$AUTOPKGTEST_TMP/out.mp4" --wait \
	| json result data state | grep -qx completed
openshot-cli project save "$AUTOPKGTEST_TMP/test.osp" | json result data path

python3 - "$AUTOPKGTEST_TMP/out.mp4" <<'PY'
import sys
import openshot
r = openshot.FFmpegReader(sys.argv[1])
r.Open()
info = r.info
print("exported:", info.width, "x", info.height, info.vcodec, info.acodec,
      round(info.duration, 2), "s")
assert (info.width, info.height) == (1280, 720)
assert info.has_video and info.has_audio
assert abs(info.duration - 2.0) < 0.2
r.Close()
PY
echo "cli-export: OK"
