
import glob
import os
import re
import shutil
import shlex
import subprocess
import sys
from urllib.parse import urlparse
from urllib.parse import ParseResult
import zipfile

from sys import platform as platform

import requests

WINDOWS_PLATFORMS = ['win32', 'win64']
LINUX_PLATFORMS = ['linux', 'linux2']

def printos(os, bits):
    """Prints the operating system and bit size"""
    print('Detected {} {} bit'.format(os, bits))

def add():
    """Installs the fea tools on windows/mac/linux"""
    osname = None
    is_64bit = sys.maxsize > 2**32
    bitsize_dict = {True: 64, False: 32}
    bitsize = bitsize_dict[is_64bit]
    if platform in LINUX_PLATFORMS:
        printos('Linux', bitsize)
        ubuntu_add()
    elif platform == "darwin":
        printos('Mac OS X', bitsize)
        mac_add()
    elif platform in WINDOWS_PLATFORMS:
        printos('Windows', bitsize)
        windows_add(bitsize)
    print('Done!')

def remove():
    """Removes the fea tools on windows/mac/linux"""
    osname = None
    is_64bit = sys.maxsize > 2**32
    bitsize_dict = {True: 64, False: 32}
    bitsize = bitsize_dict[is_64bit]
    if platform in LINUX_PLATFORMS:
        printos('Linux', bitsize)
        ubuntu_remove()
    elif platform == "darwin":
        printos('Mac OS X', bitsize)
        mac_remove()
    elif platform in WINDOWS_PLATFORMS:
        printos('Windows', bitsize)
        windows_remove(bitsize)
    print('Done!')

def ubuntu_add():
    """Adds ccx and gmsh programs on ubuntu, uses apt"""
    gmsh_installed = shutil.which('gmsh')
    if not gmsh_installed:
        print('Installing gmsh')
        command_line = "sudo apt-get install gmsh"
        subprocess.check_call(command_line, shell=True)
    else:
        print('gmsh present')
    ccx_installed = shutil.which('ccx')
    if not ccx_installed:
        print('Installing calculix (ccx)')
        command_line = "sudo apt-get install calculix-ccx"
        subprocess.check_call(command_line, shell=True)
    else:
        print('calculix (ccx) present')

def ubuntu_remove():
    """Removes ccx and gmsh programs on ubuntu, uses apt"""
    ccx_installed = shutil.which('ccx')
    if not ccx_installed:
        print('calculix (ccx) is not on your system')
    else:
        print('Removing calculix (ccx)')
        command_line = "sudo apt-get remove calculix-ccx"
        subprocess.check_call(command_line, shell=True)
    gmsh_installed = shutil.which('gmsh')
    if not gmsh_installed:
        print('gmsh is not on your system')
    else:
        print('Removing gmsh')
        command_line = "sudo apt-get remove gmsh"
        subprocess.check_call(command_line, shell=True)

def mac_add():
    """Adds ccx and gmsh programs on mac, uses brew"""
    brew_installed = shutil.which('brew')
    if not brew_installed:
        print('Installing brew')
        url = 'https://raw.githubusercontent.com/Homebrew/install/master/install'
        command_line = "/usr/bin/ruby -e \"$(curl -fsSL %s)\"" % url
        subprocess.check_call(command_line, shell=True)
    else:
        print('brew present')
    gmsh_installed = shutil.which('gmsh')
    if not gmsh_installed:
        print('Installing gmsh')
        folder_path = os.path.dirname(os.path.abspath(__file__))
        dmginstall_path = os.path.join(folder_path, 'dmginstall.sh')
        url = 'http://gmsh.info/bin/MacOSX/gmsh-3.0.5-MacOSX.dmg'
        command_line = '%s %s' % (dmginstall_path, url)
        print('command_line=%s' % command_line)
        subprocess.check_call(command_line, shell=True)
        gmsh_path = '/Applications/Gmsh.app/Contents/MacOS/gmsh'
        command_line = "ln -s %s /usr/local/bin/gmsh" % gmsh_path
        subprocess.check_call(command_line, shell=True)
    else:
        print('gmsh present')
    ccx_installed = shutil.which('ccx')
    if not ccx_installed:
        mac_add_ccx()
    else:
        print('calculix (ccx) present')

def mac_add_ccx():
    print('Installing calculix (ccx)')
    command_line = "brew install brewsci/science/calculix-ccx"
    subprocess.check_call(command_line, shell=True)
    ccx_path = find_brew_binary_location('calculix-ccx', 'ccx')
    if not ccx_path:
        raise Exception('Failed to find ccx binary')
    # link the ccx command to the ccx binary
    command_line = "ln -s %s /usr/local/bin/ccx" % ccx_path
    subprocess.check_call(command_line, shell=True)
    # check to see if we have the fortran that ccx needs and return if we do
    gcc7_to_path = "/usr/local/opt/gcc/lib/gcc/7"

    needed_fortran_path = "%s/libgfortran.4.dylib" % gcc7_to_path
    if os.path.isfile(needed_fortran_path):
        if os.path.islink(link_to_path):
            print('Linked gcc7 fortran found and used')
        else:
            print('System gcc7 fortran found and used')
        print('Finished installing calculix (ccx)')
        return
    # install gcc@7 with brew if we don't have it
    paths = glob.glob("/usr/local/Cellar/gcc@7/*")
    if not paths:
        command_line = "brew install gcc@7"
        subprocess.check_call(command_line, shell=True)
        print('Installed gcc@7 (needed by calculix)')
        paths = glob.glob("/usr/local/Cellar/gcc@7/*")
    # link gcc@7 from_path to to_path
    gcc7_from_path = "%s/lib/gcc/7" % paths[-1]
    command_line = "ln -s %s %s" % (gcc7_from_path, gcc7_to_path)
    subprocess.check_call(command_line, shell=True)
    if not os.path.isfile(needed_fortran_path):
        raise Exception("Install failed, libgfortran.4.dylib (a library that "
                        "ccx needs) was NOT FOUND")
    print('Finished installing calculix (ccx)')


def find_brew_binary_location(package_folder, search_string):
    """Finds the location of a binary installed by homebrew"""
    match_str = '/usr/local/Cellar/%s/**/*%s*' % (package_folder,
                                             search_string)
    paths = glob.glob(match_str, recursive=True)
    for path in paths:
        if os.access(path, os.X_OK):
            return path
    return None

def mac_remove():
    """Removes ccx and gmsh programs on mac, uses brew"""
    brew_installed = shutil.which('brew')
    if not brew_installed:
        print('Installing brew')
        url = 'https://raw.githubusercontent.com/Homebrew/install/master/install'
        command_line = "/usr/bin/ruby -e \"$(curl -fsSL %s)\"" % url
        subprocess.check_call(command_line, shell=True)
    else:
    
    print('brew present')
    ccx_installed = shutil.which('ccx')
    if not ccx_installed:
        prin
t('calculix (ccx) is not on your system')
    else:
        print('Removing calculix (ccx)')
        # remove link to ccx
        command_line = "rm /usr/local/bin/ccx"
        subprocess.check_call(command_line, shell=True)
        print('Calculix (ccx) symlink was removed')
        # remove binary
        command_line = "brew uninstall calculix-ccx"
        subprocess.check_call(command_line, shell=True)
        print('Calculix (ccx) binary was removed')
        # remove gcc7 link if it exists
        gcc7_sys_path = "/usr/local/opt/gcc/lib/gcc/7"
        if os.path.islink(gcc7_sys_path):
            command_line = "rm %s" % gcc7_sys_path
            subprocess.check_call(command_line, shell=True)
            print('gcc@7 symlink was removed (it was needed by calculix)')
        # remove gcc@7 if it exists
        gcc7_brew_path = "/usr/local/Cellar/gcc@7"
        if os.path.isdir(gcc7_brew_path):
            command_line = "brew uninstall gcc@7"
            subprocess.check_call(command_line, shell=True)
            print('gcc@7 was removed (it was needed by calculix)')

    gmsh_installed = shutil.which('gmsh')
    if not gmsh_installed:
        print('gmsh is not on your system')
    else:
        print('Removing gmsh')
        command_line = "rm /usr/local/bin/gmsh"
        subprocess.check_call(command_line, shell=True)
        command_line = "rm -rf /Applications/Gmsh.app"
        subprocess.check_call(command_line, shell=True)


def windows_add(bitsize):
    """Adds ccx and gmsh programs on windows"""
    gmsh_installed = shutil.which('gmsh')
    if not gmsh_installed:
        print('Installing gmsh')
        url = 'http://gm