#!/usr/bin/env python

import argparse
import os
import re

from iniparse import ConfigParser, DuplicateSectionError

parser = argparse.ArgumentParser(description='Add a new tito releaser')
parser.add_argument('rhel_branch', help='rhel_branch (ex. rhel-7.3)')
parser.add_argument('placeholder_bz', help='bug id of placeholder bz (ex. 1328559)')

args = parser.parse_args()

''' Produces something like follows
[rhel-7.3]
releaser = tito.release.DistGitReleaser
branches = rhel-7.3
required_bz_flags = rhel-7.3.0+
placeholder_bz = 1328559
'''
config = ConfigParser()
config.read('rel-eng/releasers.conf')
try:
    config.add_section(args.rhel_branch)
except DuplicateSectionError:
    pass  # we'll ignore this.
config.set(args.rhel_branch, 'releaser', 'tito.release.DistGitReleaser')
config.set(args.rhel_branch, 'branches', args.rhel_branch)
config.set(args.rhel_branch, 'required_bz_flags', '{}.0+'.format(args.rhel_branch))
config.set(args.rhel_branch, 'placeholder_bz', args.placeholder_bz)

with open('rel-eng/releasers.conf', 'wb') as configfile:
    config.write(configfile)

pretty_version = re.match('rhel-(.*)', args.rhel_branch).group(1)
print('tito releaser created.')
command = './build.sh && git commit -a -m "{bz}: Rebase subscription-manager-migration-data component to the latest upstream branch for RHEL {rhel_version}"'.format(bz=args.placeholder_bz, rhel_version=pretty_version)
if raw_input('build and commit? (y/n) ').strip().lower() == 'y':
    os.system(command)
else:
    print('suggested commands for later:')
    print(command)
