#!/bin/bash

# Thanks to Robert Siemer (825924/robert-siemer) on SO; https://stackoverflow.com/a/29754866
set -o errexit -o pipefail -o noclobber -o nounset
! getopt --test > /dev/null 
if [[ ${PIPESTATUS[0]} -ne 4 ]]; then
    echo '`getopt --test` failed in this environment.'
    exit 1
fi

OPTIONS=m:
LONGOPTS=manifest:
! PARSED=$(getopt --options=$OPTIONS --longoptions=$LONGOPTS --name flatpak_vendor -- "$@")
if [[ ${PIPESTATUS[0]} -ne 0 ]]; then
    # e.g. return value is 1
    #  then getopt has complained about wrong arguments to stdout
    exit 2
fi
eval set -- "$PARSED"

manifest=""
while true; do
	case "$1" in
		-m|--manifest)
			manifest="$2"
			shift 2
			;;
		--)
			shift
			break
			;;

		*)
			echo "Unexpected arg"
			exit 3
			;;
	esac
done

if [[ ! -z ${manifest} ]]; then
	cat ${manifest} | yq -y > flatpak.yaml
fi

flatpak-builder buildservice --download-only flatpak.yaml
