#!/usr/bin/python3
# -*- coding: latin1 -*-
# $Id$
#
# Author:	Vasilis.Vlachoudis@cern.ch
# Date:	29-Mar-2012

__author__ = "Vasilis Vlachoudis"
__email__  = "Vasilis.Vlachoudis@cern.ch"

import os
import re
import sys
import configparser

CLEAR     = "\033[2J"
BOLD      = "\033[1m"
UNDERLINE = "\033[4m"
REVERSE   = "\033[7m"
NORMAL    = "\033[m"

# MINIMUM VERSIONS
FLAIR_VERSION = "3.2-4.5"
FLUKA_VERSION = "4-3.3"
FLUKA_NEUTRON_DB  = "JEFF-3.3"
FLUKA_NEUTRON_VER = "1.1"

# MacOS?
isDarwin = sys.platform.startswith('darwin')

warnings = 0

#-------------------------------------------------------------------------------
def abort(w,title,hlp):
	global warnings

	print("%s%s %s %s%s"%("="*30,BOLD,w,NORMAL,"="*30))
	print("%s%s%s"%(BOLD,title,NORMAL))
	print(hlp)
	print("="*70)
	if w=="ERROR":
		sys.exit(0)
	else:
		warnings += 1

#-------------------------------------------------------------------------------
def versionNum(version):
	ver = re.sub("[.-]"," ",version).split()
	v = int(ver[0])
	r = int(ver[1])
	try:
		m = int(ver[2])
	except:
		m = 0
	try:
		n = int(ver[3])
	except:
		n = 0
	return v*10000 + r*100 + m + n/10

# Check subprocess needed later
print("\nChecking python")
try:
	from subprocess import *
except:
	abort("ERROR",
		"python is old version and do not have the 'subprocess' module",
		"""
Install the latest version of python-3 for your system.
Recommended version: 3.6.+
Possible commands (as superuser):
Fedora, RedHast, Scientific Linux, CentOS, Suse:
	dnf -y install python
Ubuntu:
	apt install python
MacOS (Macport recommended):
	port install python
		""")

# Check Python Version
if sys.version_info[0] < 3 or \
   sys.version_info[1] < 6:
	abort("ERROR",
		"flair only works with only with python V3.6+ and above",
		"""
Flair doesn't work with python V2.
Install the latest version of python-3 for your system.
Recommended version: 3.6+
Possible commands (as superuser):
Fedora, RedHast, Scientific Linux, CentOS, Suse:
	dnf -y install python3
Ubuntu:
	apt install python3
MacOS (Macport recommended):
	port install python3

If multiple python versions are present in the system ensure that flair is
using the proper one by setting the environment variable PYTHON
		""")
print("\tVersion: %d.%d-%d ok"%(sys.version_info[0],sys.version_info[1],sys.version_info[2]))

# Tkinter
print("\nChecking python tkinter module")
try:
	import tkinter
except:
	abort("ERROR",
		"Tkinter library is missing",
		"""
Install the latest 'tkinter' library compatible with your python
Possible commands (as superuser):
Fedora, RedHast, Scientific Linux, CentOS:
	dnf -y install tkinter
Suse:
	dnf -y install python3-tk
Ubuntu, Debian:
	apt install python3-tk
MacOS (Macport recommended):
	port install py37-tkinter
		""")
print("\ttkinter found")

# Check Tkinter version
print("\nChecking tk library")
if tkinter.TclVersion < 8.5:
	abort("WARNING",
		"Old Tcl %g found"%(tkinter.TclVersion),
		"""
Install the latest 'tkinter' library compatible with your python
		""")
print("\tTk Version=", tkinter.TclVersion,"ok")

# PIL
print("\nChecking python imaging")
try:
	import PIL.Image
	import PIL.ImageTk
except:
	abort("ERROR",
		"Python imaging library is missing",
		"""
Install the latest 'python imaging' and its tk interface compatible with your python
Possible commands (as superuser):
Fedora, RedHast, Scientific Linux, CentOS, Suse:
	dnf -y install python-imaging-tk
Ubuntu, Debian:
	apt install python-imaging-tk
MacOS (Macport recommended):
	port install py37-Pillow
		""")
print("\tpython-imaging-tk installed")

# xterm
#print "\nChecking xterm"
#p = Popen("which --skip-alias xterm", shell=True, stdout=PIPE, close_fds=True)
#xterm = None
#while True:
#	line = p.stdout.readline().decode()
#	if line=="": break
#	if line.find(" no xterm in ")<0:
#		xterm = line.strip()
#if xterm is None:
#	abort("ERROR",
#		"xterm program is not found",
#		"""
#Install the xterm program with
#Possible commands (as superuser):
#Fedora, RedHast, Scientific Linux, CentOS, Suse:
#	dnf -y install xterm
#Ubuntu, Debian:
#	apt install xterm
#		""")
#else:
#	print "\txterm ok"

# Gnuplot
print("\nChecking gnuplot")
gnuplot = Popen("gnuplot", shell=True, stdin=PIPE, stdout=PIPE, stderr=PIPE)

gnuplot.stdin.write("show version\n".encode())
gnuplot.stdin.write("quit\n".encode())
gnuplot.poll()
if gnuplot.returncode is not None:
	abort("ERROR",
		"gnuplot not found. Message: %s"%(gnuplot.stderr.readline().decode()),
		"""
Install the latest 'gnuplot'
Possible commands (as superuser):
Fedora, RedHast, Scientific Linux, CentOS, Suse:
	dnf -y install gnuplot
Ubuntu, Debian:
	1st enable the universe source with:
		Go to "System Settings" -> "Software Sources"
		On the "Ubuntu Software" tab
		Check the "Community-maintained Open Source software (universe)"
	Then install gnuplot from the command line
		apt update
		apt install gnuplot-x11
MacOS (Macport recommended):
	port install gnuplot

Warning: gnuplot V4.4.3 has some problems with the color palette
		""")
else:
	i,o = gnuplot.communicate()
	for line in o.splitlines():
		m = re.match(r".*Version (\d+)\.(\d+) patchlevel \b(\S+)\b .*",line.decode(),re.M|re.S)
		if m:
			version = int(m.group(1))
			release = int(m.group(2))
			try:
				patch = int(m.group(3))
			except:
				patch = -1
			break
	else:
		version = 0
		release = -1
		patch   = -1
	gnuplot.stdin.close()

	if version < 4 or (version==4 and release<2):
		abort("ERROR",
			"gnuplot not found" if version==0 else \
				"gnuplot too old %d.%d.%d"%(version,release,patch),
			"""
Install the latest 'gnuplot'
Possible commands (as superuser):
Fedora, RedHast, Scientific Linux, CentOS, Suse:
	dnf -y install gnuplot
Ubuntu, Debian:
	1st enable the universe source with:
		Go to "System Settings" -> "Software Sources"
		On the "Ubuntu Software" tab
		Check the "Community-maintained Open Source software (universe)"
	Then install gnuplot from the command line
		apt update
		apt install gnuplot-x11
MacOS (Macport recommended):
	port install gnuplot

Warning: gnuplot V4.4.3 has some problems with the color palette
			""")

	if version==4 and release==4 and patch==3:
		abort("WARNING",
			"gnuplot %d.%d.%d has a problem with the color palette"%(version,release,patch),
			"""
The problem exist only with 'x11' as terminal of gnuplot
Either, install a higher 'gnuplot' version 4.4.4+ or 4.4.2
Or, modify in flair "Tools->Preferences->Gnuplot"
the terminal to "wxt". But ensure that wxt is working
			""")
print("\tgnuplot %d.%d.%d ok"%(version,release,patch))

# Check system memory
print("\nChecking memory")
ram = 0
swap = 0
if isDarwin:
	cmd = "sysctl hw.memsize vm.swapusage"
else:
	cmd = "cat /proc/meminfo"
p = Popen(cmd, shell=True, stdout=PIPE, close_fds=True)
while True:
	line = p.stdout.readline().decode()
	if line=="": break
	s = line.split()
	if not s:
		pass
	elif s[0] == "MemTotal:":
		ram = int(s[1]) # kB
	elif s[0] == "SwapTotal:":
		swap = int(s[1]) # kB
	#MacOS
	elif s[0] == "hw.memsize:":
		ram = int(s[1]) / 1024 # kB
	elif s[0] == "vm.swapusage:":
		m = re.match(r".* total = (\d+.\d+)M .*",line)
		if m: swap = float(m.group(1)) * 1024 #kB

total = ram + swap

if ram == 0:
	abort("WARNING",
		"Unable to determine RAM",
		"Please ensure a minimum of 1 GB of RAM (not swap).")
elif ram < 1024*1024:
	abort("WARNING",
		"Not enough RAM %d kB to run FLUKA and flair "%(ram),
		"Please increase RAM to minimum 1GB.")
else:
	print("\tRam: %d kb ok"%(ram))

if swap == 0:
	abort("WARNING",
		"Unable to determine SWAP space",
		"Please ensure a minimum of 512 MB of SWAP space.")
elif swap < 512*1024:
	abort("WARNING",
		"Not enough SWAP %d kB to run FLUKA and flair "%(swap),
		"Please increase SWAP to minimum 512MB.")
else:
	print("\tSwap: %d kb ok"%(swap))

# Check CPU
print("\nChecking CPU")
ncpu = 0
cpufreq = 0

p = Popen("uname -m", shell=True, stdout=PIPE, close_fds=True)
while True:
	line = p.stdout.readline().decode()
	if line=="": break
	arch = line.strip()

if isDarwin:
	cmd = "sysctl hw.ncpu hw.cpufrequency"
else:
	cmd = "cat /proc/cpuinfo"
p = Popen(cmd, shell=True, stdout=PIPE, close_fds=True)
while True:
	line = p.stdout.readline().decode()
	if line=="": break
	s = line.split()
	if not s: continue
	if s[0] == "processor":
		ncpu = max(ncpu, int(s[2]))+1
	elif s[0] == "cpu" and s[1] == "MHz":
		cpufreq = float(s[3])
	#MacOS
	elif s[0] == "hw.ncpu:":
		ncpu = int(s[1])
	elif s[0] == "hw.cpufrequency:":
		cpufreq = int(s[1]) / 1e6 #MHz

if ncpu == 0 or cpufreq == 0:
	abort("WARNING",
		"Unable to determine CPU type/speed",
		"Please ensure a minimum of 1.0 GHz of CPU speed..")
elif cpufreq < 1024:
	abort("WARNING",
		"Slow CPU speed %g MHz "%(cpufreq),
		"Please ensure you are not in PowerSaving mode.")
else:
	print("\tCPUs: %d ok"%(ncpu))
	print("\tClock: %g MHz ok"%(cpufreq))
	print("\tArch: %s"%(arch))

# Check x11 for 32 bit a high resolution
# Check CPU
print("\nChecking X11")
width = height = depth = 0
p = Popen("xdpyinfo", shell=True, stdout=PIPE, close_fds=True)
while True:
	line = p.stdout.readline().decode()
	if line=="": break
	s = line.split()
	if not s: continue
	if s[0] == "dimensions:":
		if width==0:
			width, height = list(map(int,s[1].split("x")))
	elif s[0]=="depth" and s[1]=="of" and s[2]=="root":
		depth = int(s[4])

if width == 0 or depth == 0:
	abort("WARNING",
		"Unable to determine X11 dimensions and pixel depth",
		"""
Please ensure a minimum of 1280x768 with 24bit depth.
Install the xorg-x11-utils package to be able to determine the x11 dimensions
Possible commands (as superuser):
rpm based:
	dnf -y install xorg-x11-utils
deb based:
	apt install xorg-x11-utils
		""")
else:
	if width < 1280 or height<768:
		abort("WARNING",
			"Screen dimensions too small %dx%d"%(width,height),
			"Please ensure a minimum of 1280x768 with 24bit depth.")
	if depth < 24:
		abort("ERROR",
			"Pixel depth too small %d bit"%(depth),
			"flair works only with minimum 24 bit depth.")
	print("\tX11 dimension: %dx%d ok"%(width,height))
	print("\tX11 depth: %d ok"%(depth))

# Check flair
print("\nChecking flair")
if isDarwin:
        cmd = "which flair"
else:
        cmd = "which --skip-alias flair"
try:
	flairdir = "/usr/local/flair"
	#flairdir = "which --skip-alias flair"
	os.stat(flairdir)
except:
	print("\t flair not in standard directory")
	flairdir = ""
	p = Popen(cmd, shell=True, stdout=PIPE, close_fds=True)
	while True:
		line = p.stdout.readline().decode()
		if line=="": break
		if line.find(" no flair in ")<0:
			flairdir = os.path.dirname(line.strip())

	if not flairdir:
		abort("WARNING",
			"flair found",
			"""
Please install the latest version of flair.
If it is already installed please add flair to your PATH
Possible commands (as superuser):
Fedora, RedHast, Scientific Linux, CentOS, Suse:
	rpm -ivh --nodeps http://cern.ch/flair/download/flair-%s.noarch.rpm
Ubuntu:
	Strongly recommended to install the flair repository, so you
	can benefit automatically from the flair updates.
	Instructions at:  http://cern.ch/flair/download.html

	Alternatively you can manually install the debian package
	Download flair-%s_all.deb from the http://cern.ch/flair/download.html
	and install with
		dpkg -i flair-%s_all.deb
MacOS:
	Follow the instructions on http://cern.ch/flair/download.html
For more information please look in the flair readme file
			"""%(FLAIR_VERSION, FLAIR_VERSION, FLAIR_VERSION))
	while True:
		try:
			s = os.stat("%s/flair.py"%(flairdir))
			break
		except:
			print("\t%s/flair.py not found"%(flairdir))
			sys.stdout.write("Enter flair directory: ")
			flairdir = os.path.expandvars(os.path.expanduser(input()))
			if flairdir=="":
				sys.exit(0)
print("\tflair directory: %s"%(flairdir))

# Check flair version
sys.path.append(flairdir)
sys.path.append("%s/lib"%(flairdir))
try:
	import tkFlair
except:
	abort("ERROR",
		"Cannot load flair from directory %s"%(flairdir),
		"Please verify flair installation")

print("\tflair version:",tkFlair.__version__)

if int(tkFlair.__version__.split(".")[0]) != 3:
	abort("ERROR",
		"Invalid flair version found",
		f"""
flair located at: {flairdir}
is an obsolete version
Please install the latest version V3 from
            http://cern.ch/flair
""")

# Check geoviewer
print("\nChecking flair-geoviewer")
try:
	os.stat("%s/geoviewer.so"%(flairdir))
except:
	abort("ERROR",
		"Module: %s/geoviewer.so not found in flair directory"%(flairdir),
		"""
Please install the flair-geoviewer package,
rpm based:
	rpm -ivh flair-geoviewer-X.Y-Z.ARCH.rpm
deb based:
	dpkg -i flair-geoviewer_X.Y-Z_ARCH.deb
from source:
	follow the installation instructions in the flair README file
where: X.Y-Z is the latest flair version
	ARCH is the appropriate architecture for your machine
	If there is not available for your machine please try to
	compile and install from source (tgz)
		""")

try:
	import geoviewer

except:
	print(sys.exc_info()[1], file=sys.stderr)
	abort("ERROR",
		"geoviewer module cannot be loaded",
		"""
Please install the CORRECT flair-geoviewer package for your LINUX architecture,
rpm based:
	rpm -ivh flair-geoviewer-X.Y-Z.ARCH.rpm
deb based:
	dpkg -i flair-geoviewer_X.Y-Z_ARCH.deb
from source (prefered):
	follow the instructions in the flair README file.
where: X.Y-Z is the latest flair version
	ARCH is the appropriate architecture for your machine
	If there is not available for your machine please try to
	compile and install from source (tgz)
		""")

if versionNum(tkFlair.__version__) < versionNum(FLAIR_VERSION):
	abort("WARNING",
		"flair version %s found, expected minimum %s"%(tkFlair.__version__, FLAIR_VERSION),
		"""
Please install the latest flair & flair-geoviewer version.
Website: http://cern.ch/flair/download.html
		""")
else:
	print("\tflair version ok (same or higher than %s)"%(FLAIR_VERSION))

print("\tflair-geoviewer version",geoviewer.__version__)
if geoviewer.__version__ != tkFlair.__version__:
	abort("ERROR",
		"Version mismatch flair <> flair-geoviewer",
		"Please install the same version of flair-geoviewer and flair package")
else:
	print("\tflair and geoviewer version match")


# Check gfortran
print("\nChecking gfortran")

with open("test.f","w") as f:
	print("         program test", file=f)
	print("         write(*,*) 'Hello'", file=f)
	print("         stop", file=f)
	print("         end", file=f)

gfortran = None
p = Popen("gfortran -v", shell=True, stderr=PIPE, close_fds=True)
while True:
	line = p.stderr.readline().decode()
	if line=="": break
	if line.find("gcc version")>=0:
		gfortran = line.split()[2]
		break

if gfortran is None:
	abort("WARNING",
		"gfortran fortran not found",
		"""
Please install the latest gfortran version
Fedora, RedHast, Scientific Linux, CentOS, Suse:
	dnf -y install gfortran
Ubuntu:
	apt install gfortran
MacOS (Macport recommended):
	port install gcc9
		""")

else:
	print("\tgfortran version",gfortran)
	if int(gfortran.split(".")[0]) < 7:
		abort("WARNING",
			"gfortran version too old",
			"Please install the latest gfortran version")

	# Check if it works
	err = False
	p = Popen("gfortran test.f", shell=True, stderr=PIPE, close_fds=True)
	while True:
		line = p.stderr.readline().decode()
		if line=="": break
		if line.strip() != "":
			print(line[:-1])
			err = True

	if err:
		abort("WARNING",
			"gfortran not working properly",
			"Please install the latest gfortran version")

	else:
		p = Popen("./a.out", shell=True, stdout=PIPE, close_fds=True)
		while True:
			line = p.stdout.readline().decode()
			if line=="": break
			if line.strip() == "Hello":
				break
			else:
				err = True

		if err:
			abort("WARNING",
				"gfortran fortran is not compiling ok",
				"Please install the latest gfortran")
		else:
			print("\tgfortran function properly")

try:
	os.remove("test.f")
	os.remove("a.out")
except:
	pass

# Check Fluka
print("\nChecking FLUKA")
locations = os.getenv("PATH").split(":")
locations.append("/usr/local/fluka/bin")
try:
	config = configparser.ConfigParser()
	config.read(os.path.expanduser("~/.config/flair/flair.ini"))
	locations.insert(0,config.get("Fluka","directory") + "/bin")
except:
	pass

for flukadir in locations:
	filename = os.path.join(flukadir, "fluka")
	if os.path.isfile(filename) and os.access(filename, os.X_OK):
		flukadir = os.path.dirname(flukadir)
		print("\tFLUKA directory:",flukadir)
		break
else:
	abort("ERROR",
		"fluka not found in path nor in flair settings",
		"""
Either:
1. open flair and setup in the preferences the fluka path
2. edit your shell init script like ~/.bash_profile or ~/.tcshrc
   and add in the PATH environment variable the fluka directory
""")

fluka = None
try:
	with open(f"{flukadir}/Version.tag","r") as f:
		fluka = f.readline().split()[-1]
except:
	abort("ERROR",
		f"fluka Version.tag file not found in FLUKA {flukadir} directory",
		"Please install correctly FLUKA and set the PATH environment variable")

print("\tFLUKA Version=",fluka)
if versionNum(fluka) < versionNum(FLUKA_VERSION):
	abort("WARNING",
		"fluka version %s found, expected minimum %s"%(fluka, FLUKA_VERSION),
		"Please install correctly FLUKA")

# Check fluka (output returned)
try:
	os.stat(f"{flukadir}/bin/fluka")
	print(f"\t{flukadir}/bin/fluka exists")
except:
	abort("ERROR",
		f"Fluka executable {flukadir}/bin/fluka not found",
		"Please ensure you have correctly installed fluka")

# Check if latest neutron library is found
try:
	with open(f"{flukadir}/data/neutron/{FLUKA_NEUTRON_DB}/Version.tag","r") as f:
		neutronver = f.readline().split()[-1]
except:
	abort("ERROR",
		f"Latest neutron database '{FLUKA_NEUTRON_DB} not found in FLUKA",
		"Please install the default neutron database")

print(f"\t{FLUKA_NEUTRON_DB} Version= {neutronver}")
if versionNum(neutronver) < versionNum(FLUKA_NEUTRON_VER):
	abort("WARNING",
		f"fluka neutron database '{FLUKA_NEUTRON_DB} version {neutronver} found, expected minimum {FLUKA_NEUTRON_VER}"
		"Please install correctly FLUKA")

# Check utilities usbsuw, gplevbin
try:
	os.stat(f"{flukadir}/bin/flukadpm")
	os.stat(f"{flukadir}/bin/usbsuw")
	os.stat(f"{flukadir}/bin/ustsuw")
	os.stat(f"{flukadir}/bin/gplevbin")
	print(f"\t{flukadir}/bin utilities exists ok")
except:
	abort("ERROR",
		f"Fluka utilities {flukadir}/bin/* are not insatlled properly",
		"Please ensure you have correctly installed fluka")

# Check if we can compile fluka
p = Popen(f"{flukadir}/bin/lfluka -o testfluka", shell=True, stdout=PIPE, stderr=PIPE, close_fds=True)
err = None
while True:
	line = p.stderr.readline().decode()
	if line=="": break
	if line.find("ld returned")>=0:
		print(line)
		err = True

try:
	os.stat("testfluka")
except:
	err = True

if err:
	abort("ERROR",
		f"{flukadir}/bin/lfluka -o testfluka   doesn't compile/link properly",
		"""
		Please ensure you have the correct version of fluka with the appropriate compiler""")
else:
	print(f"\t{flukadir}/bin/lfluka -o testfluka   compiles ok")

# Check if fluka runs!
fluka = False
with open("test.inp","w") as f:
	print("STOP", file=f)

env={"FLUKADATA" : os.path.join(flukadir,"data")}
p = Popen("./testfluka test.inp", shell=True, stdout=PIPE, close_fds=True, env=env)
p.communicate()
with open("fort.11","r") as f:
	for line in f:
		if "End of FLUKA" in line:
			fluka = True
try:
	os.remove("test.inp")
	os.remove("fort.11")
	os.remove(".timer.out")
	os.remove("fort.15")
except: pass
if not fluka:
	abort("ERROR",
		"Fluka doesn't run properly",
		"Please ensure you have correctly compiled fluka using 'make'")
else:
	print("\tfluka runs ok")

try:
	os.remove("testfluka")
	os.remove("testfluka.map")
except:
	pass

# Epilogue
print()
print()
print("="*80)
print("Congratulations all tests passed".center(80))
print("="*80)
print()
if warnings:
	print(warnings,"warnings found")

print()
print("However this doesn't mean that everything is functioning properly")
print("Start flair, verify that the output doesn't contain any error or warning message")
print("Create a small input, run and plot the results :)")
