#!/usr/bin/env python
#
# Template file for self-extracting Pyntor presentation archives
# Copyright (C) 2005 Josef Spillner <josef@coolprojects.org>
# Available as Public Domain so everyone can freely licence presentations
# Included presentation archives and pyntor sources are licenced separately!

import base64
import os
import os.path

### Templates for presentation and pyntor sources

archive = """
%ARCHIVE%
"""

pyntor = """
%PYNTOR%
"""

### Prepare temporary directory

tempdirname = "/tmp/pyntor-selfrun.tmp"

print "[selfrun] extract into temporary directory", tempdirname
os.mkdir(tempdirname)

### Extract presentation

archivename = "pyntor-extracted-archive.tar.gz"

archivefile = tempdirname + "/" + archivename
tmpfile = archivefile + ".b64"

f = open(tmpfile, "w")
f.write(archive)
f.close()

infile = open(tmpfile)
outfile = open(archivefile, "w")

base64.decode(infile, outfile)
os.unlink(tmpfile)

infile.close()
outfile.close()

### Extract pyntor sources

pyntorname = "pyntor-extracted-sources.tar.gz"

pyntorfile = tempdirname + "/" + pyntorname
tmpfile = pyntorfile + ".b64"

f = open(tmpfile, "w")
f.write(pyntor)
f.close()

infile = open(tmpfile)
outfile = open(pyntorfile, "w")

base64.decode(infile, outfile)
os.unlink(tmpfile)

infile.close()
outfile.close()

# Run pyntor

print "[selfrun] extract pyntor from", pyntorfile
os.system("tar -C " + tempdirname + " -xzf " + pyntorfile)
os.chdir(tempdirname)

dir = None
for d in os.listdir(tempdirname):
	if os.path.isdir(d):
		dir = d
if dir:
	print "[selfrun] run pyntor in", dir, "on", archivename
	os.chdir(dir)
	os.system("./pyntor ../" + archivename)
else:
	print "[selfrun] Error: no pyntor source directory found"

# Clean up

print "[selfrun] clean up", tempdirname
os.system("rm -rf " + tempdirname)

