#!/usr/bin/env python

# Copyright (C) 2022 The University of Notre Dame
# This software is distributed under the GNU General Public License.
# See the file COPYING for details.

# python_driver takes the name of a python file and locates its dependencies via static analysis.
# This is used directly by makeflow_linker and not meant to be invoked directly

import sys
import os
import errno
import re
import warnings

# ignoring warnings here as we are working on a more comprenhensive solution
# for python linking, and there is no direct replacement of the functions we
# use of imp in importlib.
with warnings.catch_warnings():
    warnings.filterwarnings("ignore",category=DeprecationWarning)
    import imp

def usage(name):
	a  = "USAGE: %s [options] file_to_link\n" %name
	a += "Where [options] is zero or more of the following:\n"
	a += "\t-e, --use-named\tSkip builtin modules.\n"
	return a

def setup(input_filename):
	sys.path.insert(0, os.path.dirname(os.path.abspath(file_to_link)))

	try:
		f = open(file_to_link)
		f.close()
	except:
		sys.exit(1)

def find_module_names(filename):
	module_names = []
	try:
		f = open(filename)
	except IOError as e:
		if e.errno == errno.EISDIR:
			return []

	for line in f:
		m = re.match('import (.+)', line)
		if m:
			split = m.group(1).split(',')
			for s in split:
				tmp = s.split(' as ')
				if len(tmp) > 1:
					s = tmp[0]
				module_names.append(s.strip())
		m = re.match('from (.+) import', line)
		if m:
			module_names.append(m.group(1))
	f.close()
	return module_names

if len(sys.argv) < 2:
	print(usage(sys.argv[0]));
	exit(1)

file_to_link = sys.argv[-1]
setup(file_to_link)

use_named = False
if len(sys.argv) > 2 and sys.argv[1] == '--use-named':
	use_named = True

print("*Python", sys.version.split(' ')[0])
modules = find_module_names(file_to_link)
for m in modules:
	m_split = m.split('.')
	if (imp.is_builtin(m_split[0]) and use_named):
		continue
	m_path = imp.find_module(m_split[0])[1]
	if m_path != file_to_link:
		print(m_path, m)
