#!/bin/bash

set -eu
set -x

# This refreshes the org.boum.tails.TorBrowser flatpak manifest

usage() {
    cat <<EOF
Usage: $0 [--no-download] [--help]

Rebuild the org.boum.tails.TorBrowser flatpak app.

Options:
  --no-download  Don't download the latest Tor Browser Launcher flatpak.
  --help         Show this help message.
EOF
}

# Support the --no-download and --help options
NAME=$(basename "${0}")
LONGOPTS="no-download,help"
if ! getopt -Qq -o "" --longoptions $LONGOPTS -n "${NAME}" -- "$@"; then
    usage >&2
    exit 2
fi
OPTS=$(getopt -o "" --longoptions $LONGOPTS -n "${NAME}" -- "$@")
eval set -- "$OPTS"
while [ $# -gt 0 ]; do
    case $1 in
    --no-download)
        NO_DOWNLOAD=1
        shift
        ;;
    --help)
        usage
        exit 0
        ;;
    esac
    shift
done

DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
METADATA_FILE="${DIR}/metadata"

# Setup flatpak
flatpak --user remote-add --if-not-exists flathub https://flathub.org/repo/flathub.flatpakrepo

# Extract the [Application] section of the old metadata file
sed -n '/^\[Application\]/,/^\[/p' "${METADATA_FILE}" >>"${METADATA_FILE}.new"
mv "${METADATA_FILE}.new" "${METADATA_FILE}"

# Install the org.torproject.torbrowser-launcher flatpak app to
# get the updated metadata file
if [ -z "${NO_DOWNLOAD:-}" ]; then
    flatpak install --user --assumeyes --reinstall flathub org.torproject.torbrowser-launcher
fi
METADATA=$(flatpak info --show-metadata org.torproject.torbrowser-launcher)

# Extract everything except for the [Application] section of the new
# metadata
echo "${METADATA}" | sed '/^\[Application\]/,/^\[/d' >>"${METADATA_FILE}"

# Commit the changes to the git repo
git add "${METADATA_FILE}"
git commit -m "Refresh org.boum.tails.TorBrowser flatpak manifest" || exit 0
git show
