# -*- coding: latin-1 -*-

# Copyright (c) 2006 Stas Zykiewicz <stas.zytkiewicz@gmail.com>
#
#           setup.py
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Library General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.

#Script to install the GvR lessons in the GvR docs directory.

# This is a simple script, the program basicly flows from top to bottom.   
import shutil,os,sys

if os.name == 'posix':
    uid = os.popen('id -u').read()[:-1]
    if int(uid) != 0:
        print "Sorry, but only root can use this setup script."
        sys.exit(0)

class InstallError(Exception):
    pass
    
CAN_USE_TK = 0
# we define the text strings here in toplevel so they can be used by the
# frontends (Tkinter and console)
HEADER_TXT = "Can't find the GvR directory"
PATH_TXT = "Please, give the full path to the GvR directory"
QUIT_TXT = "Do you really want to quit ?"
QUIT_TXT_TITLE = "Quit?"
PATH_ERROR_TXT = "ERROR, the path does not exist." 
ERROR = "ERROR"
NO_GVR = "It seems that you don`t have GvR or GvRng installed."
WRONG_VERSION = "Your version of GvR doesn't support this lessons package.\nThe lessons will be installed in %s"
TITLE = "GvR Lessons"
INFO_TXT = "The lessons are installed"
WICKED = "It seems that you didn't give the real GvR path after all."
WICKED1 = "I will now quit.\nNext time we meet, be sure to check your paths ." 


# if we have Tkinter we use a nice Tkinter dialog, else a command line prompt.
try:
    from Tkinter import *
    from tkMessageBox import showerror,showwarning,askokcancel,showinfo
except ImportError:
    CAN_USE_TK = 0
    # override the Tkinter dialogs
    def showerror(title,txt):
        print "\n***************** %s **************\n" % title
        print txt,'\n'
    def showwarning(title,txt):
        showerror(title,txt)
    def showinfo(title,txt):
        showerror(title,txt)
else:
    CAN_USE_TK = 1
    root = Tk()
    root.title("Guido van Robot - lessons installation")
    if sys.platform[:3] == 'win':
        size = 9
    else:
        size = 12
    root.option_add("*Font","courier %d normal" % size)
    root.option_add("*Label.Font","helvetica %d bold" % size)
    root.option_add("*Menu.Font","helvetica %d normal" % size)
    root.option_add("*Button.Font","helvetica %d normal" % size)  
    
    class EntryDialog(Frame):
        def __init__(self,parent=root,txt=PATH_TXT):
            """dialog which ask the user to give the GvR path.
            txt = the question to displayed in the dialog."""
            Frame.__init__(self,parent,relief=RIDGE, bd=1)
            self.pack(fill=BOTH,expand=YES,pady=2, padx=2)
            Label(self,text=HEADER_TXT,justify=LEFT,anchor=W).\
                        pack(side=TOP,expand=YES,fill=X,padx=4, pady=1)
            Label(self,text=txt,justify=LEFT, anchor=W).\
                    pack(side=TOP,expand=YES,fill=X,padx=4, pady=1)
            ent = Entry(root)
            ent.pack(side=TOP, fill=X,padx=4,pady=1) 
            ent.focus()
            ent.bind('<Return>', (lambda event: self.fetch()))
            self.ent = ent
            btn = Button(root, text='OK', command=self.fetch)
            btn.pack(side=LEFT,fill=BOTH,expand=YES,padx=4,pady=4)
            btn = Button(root, text='Quit', command=self.quit)
            btn.pack(side=RIGHT,fill=BOTH,expand=YES,padx=4,pady=4)
            self.path = 'q'# default value. Used to check if we must exit (install_stuff)
        def fetch(self,*args):
            self.path = self.ent.get()# this wil be checked after root.quit is called
            if not os.path.exists(self.path):
                showerror(ERROR,PATH_ERROR_TXT)
                return
            root.quit()   
        def quit(self,*args):
            if askokcancel(QUIT_TXT_TITLE,QUIT_TXT):
                root.quit()
                self.path = 'q'

def install_stuff(path):
    """This does the actual copying of files.
    It uses a Tkinter dialog or a console prompt."""
    if path == 'q': sys.exit(0)
    gvrpath = path
    path = os.path.join(path,'docs')
    print path
    if os.path.exists(path):
        try:
            path = os.path.join(path,'lessons')
            if os.path.exists(path):
                shutil.rmtree(path,1)
                os.mkdir(path)
            else:
                os.mkdir(path)
            shutil.copytree('html' ,os.path.join(path,'html'))
            shutil.copytree('pdf',os.path.join(path,'pdf'))
        except Exception,info:
            showerror(ERROR,"There was a fatal error installing the package.\n The error message was:\n %s" % info)
            sys.exit(1)
        else:
            showinfo(TITLE,INFO_TXT)
    else:
        sys.path.insert(0,gvrpath)
        try:
            import version
            if version.VERSION < "0.9.3" :
                raise InstallError
        except ImportError:
            showerror(ERROR,NO_GVR)
            sys.exit(0)
        except InstallError:
            showerror(ERROR,WRONG_VERSION % path)
            try:
                os.mkdir(path)
            except Exception,info:
                showerror(ERROR,"There was a fatal error installing the package.\n The error message was:\n %s" % info)
                sys.exit(1)
            else:
                install_stuff(gvrpath)
        else:
            showerror(ERROR,WICKED+" "+WICKED1) 
            sys.exit(0)            
# We first check if GvR is installed in the default place.
# On win32 we must always ask the user where the GvR stuff
# is installed so we don't bother checking default paths in win32.
gvrpath = '/usr/local/GvR'
gvrngpath = '/usr/local/GvRng'
path = ''
if os.name == 'posix':
    if os.path.exists(gvrpath):
        path = gvrpath
    elif os.path.exists(gvrngpath):
        path = gvrngpath
    install_stuff(path)
elif CAN_USE_TK:
    e = EntryDialog()
    root.mainloop()
    install_stuff(e.path)
else:
    print HEADER_TXT
    print PATH_TXT,", or q to quit"
    path = ''
    while path != 'q':
        path = raw_input("-> ")
        if os.path.exists(path):
            break
        elif path != 'q':
            print PATH_ERROR_TXT
    install_stuff(path)
