#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Creation of self-extracting Pyntor presentations
# Copyright (C) 2006 Josef Spillner <josef@coolprojects.org>
# Published under GNU GPL conditions

import base64
import os
import sys
import getopt
#import tempfile
import atexit

### Parse command line options

templatename = "pyntor-selfrun.template"
releasefile = None
archiveonly = False

try:
	longopts = ["help", "archive", "template=", "release="]
	options = getopt.gnu_getopt(sys.argv[1:], "hat:r:", longopts)
except:
	print "Error:", sys.exc_info()[1]
	sys.exit(1)

(options, arguments) = options

for opt in options:
	(optkey, optvalue) = opt

	if optkey in ("-h", "--help"):
		print "Pyntor Selfrun - tool to create self-extracting presentations"
		print "Copyright (C) 2006 Josef Spillner <josef@coolprojects.org>"
		print "Published under GNU GPL conditions"
		print ""
		print "Synopsis: pyntor-selfrun [options] <presentation-archive>|<presentation-dir>"
		print ""
		print "Options:"
		print "[-t | --template=...] Template file to use instead of the default"
		print "[-r | --release=... ] Take pyntor files from release tarball"
		print "[-a | --archive     ] Only create archive from presentation directory"
		print "[-h | --help        ] Display this help"
		sys.exit(0)
	elif optkey in ("-t", "--template"):
		templatename = optvalue
	elif optkey in ("-r", "--release"):
		releasefile = optvalue
	elif optkey in ("-a", "--archive"):
		archiveonly = True

if len(arguments) != 1:
	print "Error: either presentation archive or presentation directory not specified"
	sys.exit(-1)

### Check if presentation archive or directory was given

filename = arguments[0]
tempname = None

try:
	contents = os.listdir(filename)
	dirname = filename + "/"
	dirname = dirname.replace("//", "/")
	dirname = dirname.split("/")[-2]
	tempname = dirname + ".pyntor"
except:
	pass

if tempname:
	#tempdir = tempfile.mkdtemp()
	tempdir = "."
	os.system("tar czf " + tempdir + "/" + tempname + " " + filename)

def cleanup(tmpfile):
	if tmpfile is not None:
		#print "(cleanup...)", tmpfile
		os.remove(tmpfile)

if archiveonly:
	if not tempname:
		print "Error: must specify a presentation directory for archive creation"
		sys.exit(-1)
	else:
		print "Created presentation archive", tempname, "from", filename
		sys.exit(0)
else:
	if tempname:
		atexit.register(cleanup, tempname)
		filename = tempname

### Get the tarball filename

if releasefile:
	pyntorname = releasefile
else:
	print "Error: pyntor release tarball argument missing"
	sys.exit(1)

### Load template file

try:
	templatefile = open(templatename)
except:
	print "Error: could not open template file", templatename
	sys.exit(1)

template = templatefile.readlines()
template = str.join("", template)
templatefile.close()

### Create tempfile with archive in base64 format

try:
	infile = open(filename)
except:
	print "Error: could not open presentation file", filename
	sys.exit(1)

packfilename = filename + ".b64"
try:
	outfile = open(packfilename, "w")
except:
	print "Error: could not write to temporary file", packfilename
	sys.exit(1)

base64.encode(infile, outfile)

infile.close()
outfile.close()

### Same for pyntor source archive

try:
	infile = open(pyntorname)
except:
	print "Error: could not open pyntor source archive", pyntorname
	sys.exit(1)

packpyntorname = pyntorname + ".b64"
try:
	outfile = open(packpyntorname, "w")
except:
	print "Error: could not write to temporary file", packpyntorname
	sys.exit(1)

base64.encode(infile, outfile)

infile.close()
outfile.close()

### Read in base64 strings and delete tempfiles

packfile = open(packfilename)
lines = packfile.readlines()
lines = str.join("", lines)
packfile.close()
os.unlink(packfilename)

packfile = open(packpyntorname)
pyntorlines = packfile.readlines()
pyntorlines = str.join("", pyntorlines)
packfile.close()
os.unlink(packpyntorname)

### Write out templates with archive string replacements

template = template.replace("%ARCHIVE%", lines)
template = template.replace("%PYNTOR%", pyntorlines)

extractorname = filename + ".selfrun.py"
try:
	extractorfile = open(extractorname, "w")
except:
	print "Error: could not write to self-extracting file", extractorname
	sys.exit(1)

extractorfile.write(template)
extractorfile.close()

os.chmod(extractorname, 0755)

print "Created self-extracting archive", extractorname

