#! /usr/bin/env python3
###############################################################################
# (c) Roger Whittaker 2015-2023
# roger@disruptive.org.uk
# Free software licenced under the GPL
###############################################################################

import cgi
import sys
from subprocess import Popen, PIPE

from config import base

f = cgi.FieldStorage()
k = list(f.keys())

it = f["iterations"].value.strip()
sc = f["scale"].value.strip()
p = f["params"].value
pars = ""
for bit in p.split():
    pars = pars + " " + bit

pp = pars.strip().replace(" ", "_")

fn = "pen" + "_" + it + "_" + sc + "-" + pp

print("Content-Type: application/pdf")
print("Content-Disposition: attachment; filename=" + fn + ".pdf\n\n")

c1 = base + "/gppg -t ps " + it + " " + sc + " " + pars
c2 = "/usr/bin/ps2pdfwr - - "

p1 = Popen(c1.split(), stdout=PIPE)
p2 = Popen(c2.split(), stdin=p1.stdout, stdout=PIPE)
p1.stdout.close()
pdf = p2.communicate()[0]

sys.stdout.flush()
sys.stdout.buffer.write(pdf)
