"""
Aug 26th 2010, Dale Hamel, University of Manitoba
 Description: Determines whether the system is OS X or linux, and creates
 the appropriate launcher on the user's desktop.

 Synopsis: python createlauncher.py
 Notes: To create the apple launcher appropriately, there MUST be a template
 application "biolegato.app" in the current working directory in a folder
 called "osx_launcher"

@modified: May 15, 2023
@author: Dale Hamel
@contact: umhameld@cc.umanitoba.ca

"""

# Automatically converted to Python3 using 2to3. Compliant with Python 2 and 3.

import os, os.path
import sys
blib = os.environ.get("BIRCHLIB")
sys.path.append(blib)

from birchlib import Birchmod

PROGRAM = "createlauncher.py: "
USAGE = "\n\tUSAGE: createlauncher.py"
BM = Birchmod(PROGRAM, USAGE)




def make_gnome_launcher(birch_dir):
    """
        Creates a launcher of the form biolegato.desktop for use on
        linux desktops such as GNOME (v2+) and KDE (v3.5+). May also work
        on other desktops such as qt, etc, but not yet tested

        @desktop_dir: the location of the user's desktop directory,
        where the launcher will be placed

        """

    launcher_str = "[Desktop Entry]\nName=Biolegato\nIcon=" + birch_dir + "/public_html/birch_black_ico.icns\nType=Application\nExec=bash -lc birch\nStartupNotify=true\nTerminal=false\n\n"

    file_name = birch_dir + "/admin/launchers/birch.desktop"

    if (birch_dir != None and not os.path.lexists(file_name)):
        write_launcher(file_name, launcher_str)
        print(PROGRAM+"Created freedesktop launcher")



def make_apple_launcher(birch_dir):
    """
        DEPRECATED
        Makes a launcher application for OS X (tested on 10.5.8) of the format
        biolegato.app. The launcher is just a wrapper for an apple script
        that calls the system biolegato, and should use system paths.

        The this method copies a template launcher called "biolegato.app"
        to the desktop that is assumed to be in the current working directory
        in adirectory called "osx_launcher", if this changes then this method
        will need to be updated.

        Once the launcher is copied, all the contents of the BIRCH directory
        specified by the environment variable $BIRCH will be symbolically
        linked into the applications resource directory under:

        ~/biolegato.app/Contents/Resources"

        @desktop_dir: the location of the user's desktop directory,
        where the launcher will be placed
        """

    base_dir = os.getcwd()
    curr_dir = base_dir

    if (not os.path.lexists(birch_dir+"/admin/launchers/biolegato.app")):
        os.chdir(birch_dir + "/script/osx_launcher")
        curr_dir = os.getcwd()
        print(PROGRAM + "Changed directory to: " + curr_dir)

        os.system("cp -r -p -f biolegato.app " + birch_dir+"/admin/launchers")



        os.chdir(birch_dir+"/admin/launchers/biolegato.app/Contents/Resources")
        curr_dir = os.getcwd()
        print(PROGRAM + "Changed directory to: " + curr_dir)

        os.system("ln -s " + birch_dir + "/* .")
        print(PROGRAM + "Made symbolic links:\n")
        os.system("ls -l | grep lrwxr-xr-x ")



def make_win_launcher(BIRCH):
    # adapted from: http://www.blog.pythonlibrary.org/2010/01/23/using-python-to-create-shortcuts/
    import os, winshell
    from win32com.client import Dispatch

    desktop = winshell.desktop()
    path = os.path.join(desktop, "BIRCH.lnk")
    target = os.path.join(BIRCH, 'script', "birch.bat")
    wDir = BIRCH
    icon = os.path.join(BIRCH, 'public_html', 'smallbirch.gif')

    shell = Dispatch('WScript.Shell')
    shortcut = shell.CreateShortCut(path)
    shortcut.Targetpath = target
    shortcut.WorkingDirectory = wDir
    shortcut.IconLocation = icon
    shortcut.save()

def write_launcher(file_name, launcher_str):
    """
        Writes the contents of launcher_str to a file specified by
        file_name, and makes that file executable

        @file_name: the fully qualified name (including path) of the file to write.
        @launcher_str: the contents to write to the file

        """


    print(PROGRAM + "Writing contents to file: " + file_name)

    out_file = open(file_name, 'w')
    out_file.write(launcher_str)
    out_file.close


    print(PROGRAM + "Setting file permissions to executable...")
    os.chmod(file_name, 0o777)



def main(BIRCH, PLATFORM):
    #This assumes either OSX or using gnome/kde, if this changes
    #this switch will need to be updated
    if (not PLATFORM == "osx-x86_64" and  PLATFORM.find("win")<0):
        make_gnome_launcher(BIRCH)


    elif(PLATFORM=="osx-x86_64" or PLATFORM=="macos-arm64" ):# working in osx
        #make_apple_launcher(BIRCH)
        pass

    elif(PLATFORM=="winxp-32"):
        make_win_launcher(BIRCH)

    else:
        print(PROGRAM+"Platform not detected or not supported, exitting")
        exit()

    print(PROGRAM + "Completed execution normally.")

if __name__=="__main__":
    if (BM.documentor() or "-test" in sys.argv):
        pass
    else:
        PLATFORM = os.environ.get("BIRCH_PLATFORM")
        BIRCH    = os.environ.get("BIRCH")

        main(BIRCH, PLATFORM)
