#!/usr/bin/python
# This code is released under terms of the GPL. see GPL.txt for liscense

import signal
import string
import sys
import time
import os
import shutil

PREFIX="/usr/local"
#PREFIX="/home/rjune/scummtest"
BINDIR=PREFIX + "/bin"
APPDIR="/usr/share/applications"

supported_games = ('pajama3', 'samnmax')
number_games = len(supported_games)

titles = {'pajama3': "Pajama Sam 3: You Are What You Eat From Your Head to Your Feet",
          'samnmax': "Sam & Max Hit the Road"
         }
files = {'pajama3': 'PAJAMA3.HEO PAJAMA3.(A) PAJAMA3.HE2 PAJAMA3.HE4', 
         'samnmax': 'samnmax/samnmax.000 samnmax/monster.sou samnmax/samnmax.001' 
        }



def findCDRom():
	cd_dirs = [] 
	f = open("/proc/mounts")
	for line in f:
		linear = string.splitfields(line, ' ')
		if ( "iso9660" == linear[2] ):
			cd_dirs.append(linear[1])
	f.close()
	return cd_dirs

def findGame(dirar):
	for dir in dirar:
		for game in supported_games:
			fileName = string.splitfields(files[game], ' ')
			if( os.path.exists(dir + "/" + fileName[0]) ):
				return [ dir , game ] 
	return ""

def installGame(game):
	print "Creating directories"
	installDir = PREFIX + "/share/games/" + game[1]
	binFile = BINDIR + "/" + game[1]
	if(not os.path.exists(installDir)):	
		os.makedirs(installDir, 0755)
	if(not os.path.exists(BINDIR)):	
		os.makedirs(BINDIR, 0755)
	if(not os.path.exists(APPDIR)):	
		os.makedirs(APPDIR, 0755)
	filear = string.splitfields(files[game[1]], ' ')

	print "Copying files"
	for fileName in filear:
		shutil.copy(game[0] + "/" + fileName, installDir)

	print "Writing script"
	fd = file(binFile, 'w')
	fd.write("#!/bin/bash\n")
	fd.write("scummvm -p " +installDir + " -n " + game[1])
	fd.close()
	os.chmod(binFile, 0755)

	print "Adding menu entry"
	fd = file(APPDIR + "/scummvm-" + game[1] + ".desktop", 'w')
	fd.write("[Desktop Entry]\n")
	fd.write("Categories=Game;ArcadeGame;X-Fedora-Extra;\n")
	fd.write("Name=" + game[1] + "\n")
	fd.write("GenericName=" + game[1] + "\n")
	fd.write("Comment=" + titles[game[1]] + "\n")
	fd.write("Exec=" + game[1] + "\n")
	fd.write("Icon=scummvm.xpm\n")
	fd.write("Terminal=false\n")
	fd.write("Type=Application\n")
	fd.write("Encoding=UTF-8\n")
	fd.write("X-Desktop-File-Install-Version=0.10\n")
	fd.close()


cd_dirs = findCDRom()

if ( 0 == len(cd_dirs) ):
	print "No CDRom mounted"
	sys.exit(1)

game = findGame(cd_dirs)
resp = raw_input('Would you like to install ' + titles[game[1]] + '? (yes/NO) ')
if ( 'yes' == resp ):
	installGame(game)
else:
	print "No game installed."
sys.exit(0)
