#!/usr/bin/python
# -*- Mode: Python; python-indent: 8; indent-tabs-mode: t -*-

import sys, os #, errno
#import datetime
import re

from preup.script_api import *


"""Preupgrade assistant performs system upgradability assessment
and gathers information required for successful operating system upgrade.
Copyright (C) 2013 Red Hat Inc.
Frantisek Kluknavsky <fkluknav@redhat.com>

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>."""
check_applies_to (check_applies="filesystem")
set_component("filesystem")
#END GENERATED SECTION
component = "vcsrepos"
# exit functions are exit_{pass,not_applicable, fixed, fail, etc.}
# logging functions are log_{error, warning, info, etc.}
# for logging in-place risk use functions log_{extreme, high, medium, slight}_risk

def main():
	if os.geteuid() != 0:
		sys.stdout.write("Need to be root.\n")
		log_slight_risk("The script needs to be run under root account")
		exit_error()
	suffixes = ("/.git\n", "/.svn\n", "/.bzr\n", "/CVS\n")
	messages = {suffixes[0]:"GIT", suffixes[1]:"SUBVERSION", suffixes[2]:"BAZAAR", suffixes[3]:"CVS"}
	with open(VALUE_ALLMYFILES,"r") as allmyfiles:
		homefiles = filter(lambda x: x.startswith((r"/home/", r"/root")) and x.endswith(suffixes), allmyfiles.readlines())
	if homefiles:
		for suffix in suffixes:
			paths = filter(lambda x: x.endswith(suffix), homefiles)
			if paths:
				solution_file("Found " + messages[suffix] + " repositories:\n")
				for path in paths:
					if suffix == suffixes[0]: #git
						try:
							with open(path[:-1]+"/config", "r") as gitconfig:
								solution_file(path[:-len(suffix)]+"\n")
								for line in gitconfig:
									url = re.match(r"\s*url\s*=\s*(.*)", line)
									if url:
										addr = re.match(r"(ftp://|https?://)(.*)", url.group(1))
										if addr:
											solution_file("url = [link: " + url.group(1) + "]\n")
										else:
											solution_file(line)
						except IOError:
							pass
					elif suffix == suffixes[1]: #svn
						try:
							with open(path[:-1]+"/entries", "r") as config:
								solution_file(path[:-len(suffix)]+"\n")
								line = config.readlines()[4]
								if re.match(r"\s*(https?|ftp)://", line):
									solution_file("url = [link: " + line[:-1] + "]\n")
								else:
									solution_file("url = " + line)
						except IOError:
							pass
					elif suffix == suffixes[2]: #bzr
						try:
							with open(path[:-1]+"/branch/branch.conf", "r") as config:
								solution_file(path[:-len(suffix)]+"\n")
								for line in config:
									addr = re.match(r"\s*parent_location\s*=\s*(.*)", line)
									if addr:
										if re.match(r"(https?|ftp)://", addr.group(1)):
											solution_file("url = [link: " + addr.group(1) + "]\n")
										else:
											solution_file("url = " + addr.group(1) + "\n")
						except IOError:
							pass
					elif suffix == suffixes[3]: #cvs
						try:
							with open(path[:-1]+"/Root", "r") as config:
								solution_file(path[:-len(suffix)]+"\n")
								for line in config:
									solution_file(line)
						except IOError:
							pass
					else:
						solution_file(path[:-len(suffix)]+"\n")
				solution_file("\n")
	else:
		solution_file("VCS repositories not found.")


if __name__ == "__main__":
	set_component(component)
	main()
	exit_informational()
