#!/usr/bin/env python

#  lyx2docx Lyx Integration Install Script
#  Copyright (c) 2014, Adam Rehn
# 
#  Script to install LyX export menu integration for lyx2docx.
# 
#  ---
#
#  Permission is hereby granted, free of charge, to any person obtaining a copy
#  of this software and associated documentation files (the "Software"), to deal
#  in the Software without restriction, including without limitation the rights
#  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
#  copies of the Software, and to permit persons to whom the Software is
#  furnished to do so, subject to the following conditions:
#
#  The above copyright notice and this permission notice shall be included in
#  all copies or substantial portions of the Software.
#
#  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
#  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
#  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
#  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
#  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
#  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
#  THE SOFTWARE.

from __future__ import print_function
import os, platform, shutil, glob

# Retrieves the contents of a file
def GetFileContents(filename):
	f = open(filename, "r")
	data = f.read()
	f.close()
	return data

# Writes the contents of a file
def PutFileContents(filename, data):
	f = open(filename, "w")
	f.write(data.encode("utf-8"))
	f.close()

# Determines the location of the LyX user directory
# Based on the info from <http://wiki.lyx.org/LyX/UserDir>
def GetLyxUserDirLocation():
	
	# Under Windows, the location is %APPDATA%/LyX<VERSION>
	system = platform.system()
	if system == "Windows":
		appdataDir = os.environ.get("APPDATA")
		matchingDirs = glob.glob(appdataDir + "/LyX*")
		if len(matchingDirs) > 0:
			return matchingDirs[ len(matchingDirs) - 1 ].replace("\\", "/")
		
	# Under Mac OS X, the location is ~/Library/Application Support/LyX-<VERSION>
	elif system == "Darwin":
		libraryDir = os.path.expanduser("~/Library/Application Support/")
		matchingDirs = glob.glob(libraryDir + "/LyX*")
		if len(matchingDirs) > 0:
			return matchingDirs[ len(matchingDirs) - 1 ].replace("\\", "/")
		
	# Under UNIX operating systems, the location is ~/.lyx
	else:
		homeDir = os.path.expanduser("~/")
		if os.path.exists(homeDir + ".lyx"):
			return homeDir + ".lyx"
	
	# Failed to determine directory location
	return ""

# Adds a line to the LyX preferences file if it does not already exist
def AddLyxPreferencesLine(lyxprefs, line):
	if lyxprefs.find(line) == -1:
		lyxprefs += "\n" + line
	return lyxprefs

# Determine the LyX user directory
userdir = GetLyxUserDirLocation()
if userdir == "":
	print("Error: failed to determine LyX user directory location!")
	sys.exit(1)

# Copy lyx2docx.py to the LyX scripts folder
shutil.copyfile(os.path.dirname(os.path.abspath(__file__)) + "/lyx2docx.py", userdir + "/scripts/lyx2docx.py")

# Add the lines to the LyX preferences file to include DOCX in the export menu (create the preferences file if it doesn't exist)
if os.path.exists(userdir + "/preferences"):
	lyxprefs = GetFileContents(userdir + "/preferences")
else:
	lyxprefs = "# Generated by the lyx2docx installer. Use LyX to generate a properly formatted copy.\n\nFormat 1\n\n"
lyxprefs = AddLyxPreferencesLine(lyxprefs, '\\format "docx" "docx" "DOCX" "" "" "" "document,menu=export"')
lyxprefs = AddLyxPreferencesLine(lyxprefs, '\\converter "lyx" "docx" "python -tt $$s/scripts/lyx2docx.py -dir $$r $$f" ""')
PutFileContents(userdir + "/preferences", lyxprefs)

# Installation complete
print("Successfully installed lyx2docx LyX integration.")
