#/bin/bash

# usage:
# commit.sh macroscop 4.2.80.6412 4.2
# commit.sh macroscop 4.2.80.6412 4.2 latest

BRAND=$1; shift
VERSION=$1; shift
TARGET_BRANCHES=("$@")

GPG_HOMEDIR="/root/.gnupg"
GPG_KEYID=80369656

mkdir ./temp

tar xzf ${BRAND}_${VERSION}.tar.gz -C ./temp

metadata() {
  local key=$1

  case $key in
    "ostree.collection-binding")
      echo $(sed '1!d' ${BRAND}_${VERSION}.metadata)
      ;;

    "xa.download-size")
      echo $(sed '2!d' ${BRAND}_${VERSION}.metadata)
      ;;

    "xa.installed-size")
      echo $(sed '3!d' ${BRAND}_${VERSION}.metadata)
      ;;

    "xa.metadata")
      echo $(sed '4!d' ${BRAND}_${VERSION}.metadata)
      ;;
  esac
}

COMMIT_HASHES=()

for branch_version in "${TARGET_BRANCHES[@]}"; do
  branch="app/com.${BRAND}.client/x86_64/${branch_version}"
  COMMIT_HASHES+=($(ostree commit -s $VERSION -b $branch --tree=dir=./temp \
    --add-metadata="ostree.collection-binding=$(metadata ostree.collection-binding)" \
    --add-metadata="ostree.ref-binding=['$branch']" \
    --add-metadata="xa.ref='$branch'" \
    --add-metadata="xa.download-size='$(metadata xa.download-size)'" \
    --add-metadata="xa.installed-size='$(metadata xa.installed-size)'" \
    --add-metadata="xa.metadata=$(metadata xa.metadata)"))
done

for commit in "${COMMIT_HASHES[@]}"; do
  ostree gpg-sign --gpg-homedir=$GPG_HOMEDIR $commit $GPG_KEYID
done

flatpak build-update-repo . --gpg-homedir=$GPG_HOMEDIR --gpg-sign=$GPG_KEYID

rm -rf ./temp
