#!/usr/bin/env python3
# vim: ft=python
# Fiercely update a branch from its remote
from __future__ import print_function

import sys
import subprocess

PYTHON=sys.executable
NEED_SHELL = True

def bt(cmd_str):
    return subprocess.check_output(cmd_str, text=True, shell=NEED_SHELL)

try:
    branchname = sys.argv[1]
except IndexError:
    branchname = 'main'

upstream = bt("git for-each-ref --format='%(upstream:short)' "
              "refs/heads/" + branchname)
if upstream == '':
    raise RuntimeError('Could not find upstream')

remote, rbranch = upstream.split('/', 1)

print('Fetching ', remote)
bt('git fetch ' + remote)
print('Resetting branch ref {0} from {1}:{2}'.format(branchname, remote, rbranch))
bt('git update-ref -m "merge: Fast forward" refs/heads/{0} {1}/{2}'.format(
    branchname, remote, rbranch))
print('Resetting staging area')
bt('git reset')
