from Tkinter import *
import tkMessageBox
import tkSimpleDialog
import os
import glob
import tkFont
from string import *
whichstep=0
selected="NONE"
player="kplayer"

print "Starting..."
os.system('mkdir /opt/giFT')
os.system('mkdir /opt/giFT/incoming')
os.system('mkdir /opt/giFT/completed')

def askyesnocancel(title,message):
   return tkMessageBox._show(title,message,'question','yesnocancel')

def compdisp():
   os.chdir("/opt/giFT/completed")
   try:
      result = glob.glob('*.*')
      try:
         res = len(result)
         if res > 0:
            compbox.delete(0, END)
            for qiso in range(0,res):
               temptxt = result[qiso]
               compbox.insert(END, temptxt)
      except:
         z = 0
   except:
      z = 0

def edk():
   os.system('kwrite /etc/apt/sources.list')

def edv():
   os.system('xterm -fn 10x20 -geometry 80x20 -sb -rightbar -e "vi /etc/apt/sources.list" ')

def update():
   os.system('xterm -fn 10x20 -geometry 80x20 -sb -rightbar -hold -e "apt-get update" ')

def ads():
   global whichstep
   dtext = "This will add a line for Debian stable to your sources.list if one does not exist, and then run \"apt-get update\".  Proceed?"
   if tkMessageBox.askyesno("Update sources?", dtext):
      z=os.system('cat /etc/apt/sources.list | grep "debian.org/debian stable" > /dev/null ')
      cattxt="\"\ndeb ftp://ftp.us.debian.org/debian stable main contrib non-free\""  
      command = "echo " + cattxt + " >> /etc/apt/sources.list"
      if z!=0:
         os.system(command)  
         tkMessageBox.showinfo("Status", "Entry added,\nwill now run apt-get update...\nPlease close window when \n all scrolling is complete...")
         update()
         whichstep=1
      else:
         tkMessageBox.showinfo("Status", "Needed entry already exists, skipping,\nwill now run apt-get update...\nPlease close window when \n all scrolling is complete...")
         update() 
         whichstep=1

def dload():
   global whichstep
   if whichstep>0:
      dtext = "Now we will download the custom packages and config files for use in the next steps. Proceed?"
      if tkMessageBox.askyesno("Download files?", dtext):
         os.chdir("/opt/giFT")
         result = glob.glob('/opt/giFT/*')
         elems = len(result)
         for qelem in range(0,elems):
            temptxt = result[qelem]
            command = "rm " + temptxt
            os.system(command)
         os.system('xterm -fn 10x20 -geometry 80x10 -sb -rightbar -e "wget http://viewoftheblue.com/itconsulting/libfasttrack-gift.deb" ')
         os.system('xterm -fn 10x20 -geometry 80x10 -sb -rightbar -e "wget http://viewoftheblue.com/itconsulting/gift-ares.deb" ')
         os.system('xterm -fn 10x20 -geometry 80x10 -sb -rightbar -e "wget http://viewoftheblue.com/itconsulting/giftd.conf" ')
         os.system('xterm -fn 10x20 -geometry 80x10 -sb -rightbar -e "wget http://viewoftheblue.com/itconsulting/openft_nodes" ')
         os.system('xterm -fn 10x20 -geometry 80x10 -sb -rightbar -e "wget http://viewoftheblue.com/itconsulting/ares_nodes" ')
         os.system('xterm -fn 10x20 -geometry 80x10 -sb -rightbar -e "wget http://viewoftheblue.com/itconsulting/apollon.deb" ')
         tkMessageBox.showinfo("Status", "Downloads complete...")
         whichstep=2
   else:
      tkMessageBox.showerror("Not in sequence", "Installation not in sequence. Please run step 1 first...")

def instdeb():
   global whichstep
   if whichstep>1:
      dtext = "Now we will install the needed Debian packages from the Debian sources.\n This may upgrade \"libc6\" and \"locales\" which rarely affects your system adversely. Choose the default answers if any dialogs come up. Close the terminal window when all activity is complete. Proceed?"
      if tkMessageBox.askyesno("Install Debian pkgs?", dtext):
         pkgnames = "libgift0 libgiftproto0 giftd libopenft-gift libgnutella-gift libncursesw5 giFTcurs "
         cdcomm = "apt-get install " + pkgnames
         command = "xterm -fn 10x20 -geometry 80x20 -sb -rightbar -sl 60000 -hold -e " + cdcomm 
         os.system(command) 
         whichstep=3           
   else:
      tkMessageBox.showerror("Not in sequence", "Installation not in sequence. Please run steps 1 and 2 first...") 

def final():
   global whichstep
   if whichstep>2:
      dtext = "Now we will install the final custom Debian packages and config files which were downloaded in step 2.\n Proceed?"
      if tkMessageBox.askyesno("Install Debian pkgs?", dtext):
         homedir=os.environ["HOME"]
         os.system('mkdir /root/.giFT')
         os.chdir("/opt/giFT")
         os.system('xterm -fn 10x20 -geometry 80x10 -sb -rightbar -e "dpkg -i libfasttrack-gift.deb" ')
         os.system('xterm -fn 10x20 -geometry 80x10 -sb -rightbar -e "dpkg -i gift-ares.deb" ')
         os.system('xterm -fn 10x20 -geometry 80x10 -sb -rightbar -e "dpkg -i apollon.deb" ')
         os.system('cp ares_nodes /root/.giFT')
         os.system('cp openft_nodes /root/.giFT')
         os.system('cp giftd.conf /root/.giFT')
         os.system('cp -a /usr/share/giFT/Ares /root/.giFT')
         os.system('cp -a /usr/share/giFT/FastTrack /root/.giFT')
         os.system('cp -a /usr/share/giFT/Gnutella /root/.giFT')
         os.system('cp -a /usr/share/giFT/OpenFT /root/.giFT')
         os.system('cp -a /usr/share/giFT/ui /root/.giFT')
         os.chdir("/root/.giFT")
         os.system('mv Ares/Ares.conf.template Ares/Ares.conf')
         os.system('mv FastTrack/FastTrack.conf.template FastTrack/FastTrack.conf')
         os.system('mv Gnutella/Gnutella.conf.template Gnutella/Gnutella.conf')
         os.system('mv OpenFT/OpenFT.conf.template OpenFT/OpenFT.conf')
         os.system('mv ui/ui.conf.template ui/ui.conf')
         os.system('mv ares_nodes Ares/nodes')
         os.system('mv openft_nodes OpenFT/nodes')
         os.chdir("/opt/giFT")
         result = glob.glob('/opt/giFT/*')
         elems = len(result)
         for qelem in range(0,elems):
            temptxt = result[qelem]
            command = "rm " + temptxt
            os.system(command)
         tkMessageBox.showinfo("Installation complete", "Installation has been completed, you may now use the interface...") 
   else:
      tkMessageBox.showerror("Not in sequence", "Installation not in sequence. Please run steps 1, 2 and 3 first...") 

def remvall():
   dtext = "This will remove all core packages installed by this app, but will not remove your downloaded files. Wait for all scrolling to complete before closing window. Are you sure?"
   if tkMessageBox.askyesno("Purge packages?", dtext):
      pkgnames = "giftd libopenft-gift libgnutella-gift giFTcurs libfasttrack-gift gift-ares apollon "
      cdcomm = "apt-get remove --purge " + pkgnames
      command = "xterm -fn 10x20 -geometry 80x20 -sb -rightbar -sl 60000 -hold -e " + cdcomm 
      os.system(command) 
      os.system('rm -rf /root/.giFT')
      os.chdir("/opt/giFT")
      result = glob.glob('/opt/giFT/*')
      elems = len(result)
      for qelem in range(0,elems):
         temptxt = result[qelem]
         command = "rm " + temptxt
         os.system(command)
      tkMessageBox.showinfo("Removal complete", "Uninstallation has been completed...") 

def apf():
   dtext = "The Apollon .deb was specifically compiled for Linspire, and may not install under other Debian versions. If Apollon won't start, run this to fix it. Do NOT run this under Linspire. It will remove the custom version, then reinstall from the Debian sources. Are you sure you want to continue?"
   if tkMessageBox.askyesno("Fix Apollon?", dtext):
      pkgname = "apollon "
      cdcomm = "apt-get remove --purge " + pkgname
      command = "xterm -fn 10x20 -geometry 80x20 -sb -rightbar -hold -e " + cdcomm 
      os.system(command) 
      cdcomm = "apt-get install " + pkgname
      command = "xterm -fn 10x20 -geometry 80x20 -sb -rightbar -hold -e " + cdcomm 
      os.system(command)
      tkMessageBox.showinfo("Status", "Reinstallation complete...")

def sgd():
   ttl="___If_error,_kill_then_retry___Close_when_finished_viewing"
   command="xterm -fn 10x20 -geometry 80x10 -hold -title " + ttl + " -e giftd -d &"
   os.system(command)

def gcs():
   command="xterm -fn 10x20 -hold -e giFTcurs &"
   os.system(command)

def kgd():
   os.system('killall -9 giftd') 
   
def apollon():
   os.system('apollon')

def ch():
   global selected
   try:
      index = compbox.curselection() 
      pos = int( index[0] )
      file = compbox.get(index)
      selected = file
   except:
      tkMessageBox.showerror("Error", "Invalid choice")

def play():
   global selected
   global player
   if selected != "NONE":
     tmpstr = tkSimpleDialog.askstring("Select Player" , "Select player to be used for playing your audio or video file.\n It must be an app that can be started from the command line.\n One of these should work, if installed:\n kplayer mplayer amarok noatun realplay xine, vlc, etc.", initialvalue = player) 
     try:
        player=tmpstr 
        filepath = player + " \"/opt/giFT/completed/" + selected + "\" &"
        os.system(filepath)
     except:
        z = 0
   else:
      tkMessageBox.showerror("Error", "No file selected")

def delentry():
   global selected
   if selected != "NONE":
      dtext = "This will delete your selected entry from the system. Are you sure?"
      if tkMessageBox.askyesno("Delete file?", dtext):
         filepath = " \"/opt/giFT/completed/" + selected + "\""
         command = "rm " + filepath
         os.system(command)
         compdisp()
         selected = "NONE"
         tkMessageBox.showinfo("Status", "File has been deleted...")
   else:
      tkMessageBox.showerror("Error", "No file selected")

def sx():
   os.system('killall -9 xine')

def aptgf():
   cdcomm = "apt-get -f install"
   command = "xterm -fn 10x20 -geometry 80x20 -sb -rightbar -hold -e " + cdcomm 
   os.system(command) 

def userinst():
   tmpstr = tkSimpleDialog.askstring("Configure for user" , "You must enter an existing user name.\n This will copy the configuration to that account,\n enabling this system. Run this as root.\n Be sure there are no spaces before or after the user name.", initialvalue = "user")  
   try:
      user=tmpstr 
      filepath = "/home/" + user
      mknewdir = "mkdir " + filepath + "/.giFT"
      rv = os.system(mknewdir)
      if rv == 0:
         command = "cp -a /root/.giFT " + filepath
         os.system(command)
         command = "cp /root/Desktop/GIFT-BOX.desktop " + filepath + "/Desktop"
         os.system(command) 
         chgpath = filepath + "/.giFT"
         command = "chown -R " + user + " " + filepath
         os.system(command)
         command = "chgrp -R " + user + " " + filepath
         os.system(command)
         tkMessageBox.showinfo("Status", "User configuration complete...") 
      else:   
         tkMessageBox.showerror("Error", "No such user,\n or already installed\nfor this user.")  
   except:
      z = 0
   
root = Tk()
root.title("GIFT-BOX - giFT Daemon and GUI Launcher for Linspire / Debian") 
root.geometry('800x600+200+100')
root.config(bg = "#FFFFCC")

about =  "Python/Tk \"Gift Box\" for Linspire / Debian by frank754 (ver-0.3)"
f0 = Label(root,text=about,bd=5,bg="Light Gray")
f0.grid(row=0,column=0,rowspan=1,columnspan=6,pady=15)

fdeb = Label(root, text="Options required for giFTcurs:",bd=5,bg="#CCCC33",font=("Helvetica",12,"bold"))
fdeb.grid(row=1,column=0,columnspan=3,ipadx=35,pady=20)

debapt= "Other options:"
fbtn = Label(root,text=debapt,bd=5,bg="#66CCFF",font=("Helvetica",12,"bold"))
fbtn.grid(row=1,column=3,columnspan=3,ipadx=25,pady=20)

AButton = Button(root, command=sgd)
AButton.configure(text="Start giFT daemon",bg="green",font=("Helvetica",14,"bold"))
AButton.grid(row=2,column=0,ipady=10)

BButton = Button(root, command=gcs)
BButton.configure(text="Start giFTcurs",bg="#66CCCC",font=("Helvetica",14,"bold"))
BButton.grid(row=2,column=1,ipady=10)

CButton = Button(root, command=kgd)
CButton.configure(text="Stop giFT daemon",bg="#FF9966",font=("Helvetica",14,"bold"))
CButton.grid(row=2,column=2,ipady=10)

DButton = Button(root, command=compdisp)
DButton.configure(text="Reload files list",bg="#FFCC00",font=("Helvetica",14,"bold"))
DButton.grid(row=2,column=3,ipady=10)

EButton = Button(root, command=apollon)
EButton.configure(text="Start Apollon",bg="#66CCCC",font=("Helvetica",14,"bold"))
EButton.grid(row=2,column=4,ipady=10)

FButton = Button(root, command=root.quit)
FButton.configure(text="Quit",fg="white",bg="red",font=("Helvetica",14,"bold"))
FButton.grid(row=2,column=5,ipady=10,padx=20)

f1 = Label(root,text="Downloaded files in /opt/giFT/completed:",bd=5,bg="#FFCC00")
f1.grid(row=4,column=0,rowspan=1,columnspan=6,pady=25)

scrollbar1 = Scrollbar(root, orient=VERTICAL)
compbox = Listbox(root, yscrollcommand=scrollbar1.set, height=10, width=86)
scrollbar1.config(command=compbox.yview)
scrollbar1.grid(row=5,rowspan=10,column=4,sticky=N+S,pady=5)
compbox.grid(row=5,column=0,rowspan=10,columnspan=5,sticky=W,pady=5)

quickhelp = "Full installation required before use.\nRun all four steps under the first two top left menu items in their exact numbered order.\ngiFTcurs requires manual starting and stopping of the daemon. Stop the daemon after your session.\nApollon will start the daemon automatically and keep respawning it, if it is stopped.\nTo completely exit Apollon, you must also quit from the tray icon, in addition to closing the main window.\nDo not run giFTcurs and Apollon at the same time, as they will confuse each other.\nUse the Reload button to show newly downloaded files in the list box, which you may then play or delete.\nThe  audio / video player option can select any installed player you choose (won't work with Lsongs).\nInstallation must be done as root, but you can later copy the configs to any user account from here, as root." 
f7 = Label(root, text=quickhelp, anchor=S, bd=15, bg="Light Green")
f7.grid(row=15,column=0,columnspan=6,pady=10)

def genhlp():
   outmsg = "The information at the bottom of the main window should be sufficient to help you get started. There are four steps to the installation. Step 1 will update your apt sources.list and run apt-get update. It will add a \"stable\" Debian source if one does not exist. Linspire users only: you should make sure your other sources (unstable, etc.) are still commented out with a #, as originally. You may edit your sources.list via the \"Extra Tools\" menu before running this. Step 2 will download custom .debs and configs (currently) from my site. Step 3 will run apt-get to install the needed packages from Debian. Step 4 will install the downloaded custom files, as well as complete all the configuration and file management work."
   tkMessageBox.showinfo("General FAQ", outmsg)

def chlp():
   outmsg = "This app will be preconfigured and ready to use once installed. To use giFTcurs (a nice GUI-within-console app), start the daemon manually, then start giFTcurs. Stop the daemon manually after your session. To run Apollon, skip the above, and simply click the Apollon button. The first time, it may take a while to get all four plugins to connect (FastTrack, Gnutella, Ares and OpenFT). The Ares protocol has changed and the currently available Linux plugin does not work as in the past. You may only see 2 users. As root, you may copy the configs to a user account, then the apps will be enabled for that user. For non-Linspire Debian, you should always use the automatic Apollon fix under \"Extra Tools\", as the .deb provided is custom for Linspire, and may either not work or wedge your system. \"apt-get -f install\" should give you a clean bill of health after running this. To select a file to play or delete, click on the line for it in the listbox first. Everything else should be fairly self-explanatory."
   tkMessageBox.showinfo("FYI's / tips", outmsg)
   
def about():
   outmsg = "Gift-Box -giFT installer / GUI front-end by frank754@bellsouth.net \n This app will only work on a Debian-based system. \nThis particular version has been tweaked for Linspire 5.0+ in several ways so as not to break the configuration.  \n This version (0.3) released on \n 24 June 2006 and is fully GPL/Open Source. \n Requirements:\nKDE-Desktop-based Debian system. It has been tested on both Linspire and Debian unstable."
   tkMessageBox.showinfo("About", outmsg)
   
menubar = Menu(root)

pkgmenu = Menu(menubar, tearoff=0)
pkgmenu.add_command(label="Step 1: Set / update Debian source", command=ads)
pkgmenu.add_command(label="Step 2: Download custom files / configs", command=dload)
pkgmenu.add_separator()
pkgmenu.add_command(label="Exit program", command=root.quit)
menubar.add_cascade(label=" Installation Prep ", menu=pkgmenu)

instmenu = Menu(menubar, tearoff=0)
instmenu.add_command(label="Step 3: Install Debian packages", command=instdeb)
instmenu.add_command(label="Step 4: Install custom modules & config files", command=final)
menubar.add_cascade(label=" Main installation ", menu=instmenu)

usermenu = Menu(menubar, tearoff=0)
usermenu.add_command(label="Install configs to user name", command=userinst)
menubar.add_cascade(label=" Configure for \"user\" ", menu=usermenu)

playmenu = Menu(menubar, tearoff=0)
playmenu.add_command(label="Choose highlighted entry", command=ch)
playmenu.add_command(label="Play chosen entry", command=play)
playmenu.add_command(label="Delete chosen entry", command=delentry)
playmenu.add_command(label="Stop xine player", command=sx)
menubar.add_cascade(label=" Play / Delete File ", menu=playmenu)

toolmenu = Menu(menubar, tearoff=0)
toolmenu.add_command(label="Edit apt sources.list with KWrite", command=edk)
toolmenu.add_command(label="Edit apt sources.list with vi", command=edv)
toolmenu.add_command(label="Apollon fix for non-Linspire Debian", command=apf)
toolmenu.add_command(label="Run apt-get -f install (unwedging tool)", command=aptgf)
menubar.add_cascade(label=" Extra Tools ", menu=toolmenu)

removemenu = Menu(menubar, tearoff=0)
removemenu.add_command(label="Remove all packages", command=remvall)
menubar.add_cascade(label=" Uninstall ", menu=removemenu)

helpmenu = Menu(menubar, tearoff=0)
helpmenu.add_command(label="Help: General Installation FAQ", command=genhlp)
helpmenu.add_command(label="Help: Certain FYI's / Tips", command=chlp)
helpmenu.add_separator()
helpmenu.add_command(label="About / System Requirements", command=about)
menubar.add_cascade(label=" Help", menu=helpmenu)

root.config(menu=menubar)

compdisp()
root.mainloop()
print "... Done!"
