#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""The module aims to handle gentoo arch-specific processes automatically.
TODO:  rewrite it using appropriate bugzilla rest-api class"""

import argparse
import os, re, sys
from bugzilla import bugtracker


def check_existence(path):

    """The function performs basic binary-existence checks"""

    if not os.path.isfile(path):
        print("Can't find: {}. Please install appropriate packages!".format(path))
        sys.exit(1)


check_existence("/usr/bin/git")
check_existence("/usr/bin/repoman")
check_existence("/usr/bin/ekeyword")

parser = argparse.ArgumentParser(description='Repomator script v1.0')
parser.add_argument('-a', '--arch', help='specify architecture', required=True)
parser.add_argument('-b', '--bug', type=int, help='specify bug number', required=True)
parser.add_argument('-e', '--email', help='specify email addrress')
parser.add_argument('-l', '--list', help='specify packages list', required=True)
parser.add_argument('-r', '--repo', help='specify repo path', required=True)

args = parser.parse_args()

arch = args.arch
bug = args.bug
email = args.email
data = args.list
repo = args.repo


with open(data, 'r') as f:
    for line in f:

        package_category = re.search(r'((?<==)\w+.\w+|\w+.\w+)', line).group(0)
        package_name = re.search(r'(?<=/).*(?=-\d)|(\w+_\w+)', line).group(0)
        package_version = re.search(r'(?<=-)\d.*?(?=\s)', line).group(0)

        os.chdir(os.path.join(repo, package_category, package_name))

        os.system("/usr/bin/ekeyword {} {}-{}.ebuild".format(arch, package_name, package_version))
        
        if arch[:1] is not "~":
            os.system("/usr/bin/repoman ci -m \"{}/{}: {} stable wrt bug #{}\"".format(package_category, package_name, arch, bug))
        else:
            os.system("/usr/bin/repoman ci -m \"{}/{}: Add {} keyword wrt bug #{}\"".format(package_category, package_name, arch, bug))

bugtracker(arch, bug)

@@ -209,13 +209,15 @@
 t os
-, re,
+%0Aimport
  sys
@@ -1082,95 +1082,8 @@
 ()%0A%0A
-arch = args.arch%0Abug = args.bug%0Aemail = args.email%0Adata = args.list%0Arepo = args.repo%0A%0A%0A
 with
@@ -1088,16 +1088,21 @@
 th open(
+args.
 data, 'r
@@ -1392,16 +1392,21 @@
 th.join(
+args.
 repo, pa
@@ -1498,16 +1498,21 @@
 .format(
+args.
 arch, pa
@@ -1561,16 +1561,21 @@
      if 
+args.
 arch%5B:1%5D
@@ -1704,28 +1704,38 @@
 age_name, ar
-ch, 
+gs.arch, args.
 bug))%0A      
@@ -1868,20 +1868,30 @@
 name, ar
-ch, 
+gs.arch, args.
 bug))%0A%0Ab
@@ -1902,17 +1902,27 @@
 acker(ar
-ch, 
+gs.arch, args.
 bug)%0A

make imports comply PEP8 again - remove needless argparse assigns