#!/usr/bin/python3

import argparse
import os
import subprocess
import urllib.request
import configparser

parser = argparse.ArgumentParser(description='AWX-RPM management')
parser.add_argument(metavar='OPERATION',help="Choose either: install, update, upgrade or config",dest='operation',choices=["install","update","upgrade","config"])

args = parser.parse_args()

command = str(args.operation)

if command == "install":
	print("Installation is not yet implemented")
elif command == "update":
	print("Getting info on latest AWX-RPM Version")
	#subprocess.run(["/usr/bin/dnf", "clean", "all"])	
	#stream = os.popen("dnf info awx-rpm |grep Version | awk -F\: '{print $2}' | awk '{$1=$1};1' | tr -d '\n'")
	#version = stream.read()
	#stream = os.popen("dnf info awx-rpm |grep Release | awk -F\: '{print $2}' | awk '{$1=$1};1' | tr -d '\n'")
	#release = stream.read()
	stream = os.popen("dnf check-update -b awx-rpm |grep awx-rpm | awk '{ print $2}' | awk '{$1=$1};1' | tr -d '\n' |sed \"s/repository//g\"")
	version = stream.read()
	print("Newest AWX-RPM Version available in repos is: "+version)
	print("Getting lastest package excludelists")
	url = "https://rpm.awx.wiki/AWX-RPM/excludelists/awx-rpm-"+version
	response = urllib.request.urlopen(url)
	data = response.read()
	excludepackages = data.decode('utf-8')
	excludeline = ""
	for each_line in excludepackages:
		package = each_line.replace("\n", ",").strip()
		excludeline = excludeline + package

	print("Setting excludelist for EPEL")
	repo = configparser.ConfigParser()
	repo.read('/etc/yum.repos.d/epel.repo')
	repo['epel']['exclude'] = excludeline
	with open('/etc/yum.repos.d/epel.repo', 'w') as repofile:
        	repo.write(repofile)

	print("Setting excludelist for PyPI")
	repo = configparser.ConfigParser()
	repo.read('/etc/yum.repos.d/_copr:copr.fedorainfracloud.org:group_copr:PyPI.repo')
	repo['copr:copr.fedorainfracloud.org:group_copr:PyPI']['exclude'] = excludeline
	with open('/etc/yum.repos.d/_copr:copr.fedorainfracloud.org:group_copr:PyPI.repo', 'w') as repofile:
		repo.write(repofile)
	print("Updating AWX-RPM")
	subprocess.run(["/usr/bin/dnf","-y", "update", "awx-rpm"])
	print("Updating Dependencies")
	subprocess.run(["/usr/bin/dnf","-y", "update"])
