#!/bin/bash

set -ex

MISSING_SOURCE="\
  tools/constraintutil\
  tools/go_fieldenum/ \
  tools/go_generics/ \
  tools/go_marshal/ \
  tools/go_stateify/ \
  vdso/ \
"

upstream_tag="$1"

if [[ -z "$upstream_tag" ]]; then
  git remote add gvisor https://github.com/google/gvisor || true
  git fetch gvisor --tags

  # Find latest upstream tag
  upstream_tag=$(git tag -l|sort -V|grep '^release-'|tail -1)
fi

# Find the corresponding commit on `go` branch
go_commit=$(git rev-list --ancestry-path "$upstream_tag"..gvisor/go|tail -1)

# Work on upstream branch
git checkout upstream
git merge --no-commit -m "$upstream_tag"  "$go_commit"

# Restore missing source
git checkout "$upstream_tag" -- $MISSING_SOURCE
# Remove broken tests
git rm -r --cached ./tools/*/tests ./tools/*/test || true
git clean -x -d -f
# Remove generated vdso
git rm ./pkg/sentry/loader/vdsodata/vdso_* || true

# Continue merge
git merge --continue || git commit -a -m "$upstream_tag"

# Create upstream/x tag
git tag -a upstream/0.0_"${upstream_tag//release-/}" -m "$upstream_tag"

# Go back to debian/sid branch
git checkout debian/sid
gbp import-ref -u 0.0_"${upstream_tag//release-/}"
