#!/bin/bash

# date: 2008-11-02 / 2008-11-24
# version: v0.1.2j
# creator: Jelle de Jong <jelledejong@powercraft.nl>
# project: openarm sbc
# licence: gplv3

# this file wont work with no $DISPLAY and requires psnup
# so imho it should check for DISPLAY at least
# like that

if [ "x$DISPLAY" == "x" ]; then
    echo "Its quite possible that you aren't executing this script from X system, or"
    echo "you don't have DISPLAY env variable set. I cannot continue because gschem won't"
    echo "work unless you set one, even with xserver with dummy output i hope"
    exit
fi

echo ';; This file may be used to print gschem schematics from the
;; command line.  Typical usage is:
;;
;;   gschem -p -o mysch.ps -s /path/to/this/file/print.scm mysch.sch
;;
;; The schematic in "mysch.sch" will be printed to the file "mysch.ps"
;;
;; documentation: less /etc/gEDA/system-gschemrc
;; documentation: less /user/share/gEDA/scheme/print.scm
;;

(log-window "later")

(output-type "limits")
(paper-size 16.54 11.69)
(output-text "ps")
(output-type "extents")
(output-orientation "landscape")
(output-color "enabled")

; You need call this after you call any rc file function
(gschem-use-rc-values)

; filename is specified on the command line
(gschem-postscript "dummyfilename")

(gschem-exit)' > ~/openarm/working/gschem/pdf/print.scm

pdf_dir="$HOME/openarm/working/gschem/pdf"
sch_dir="$HOME/openarm/working/gschem/sch"
project="openarm-sbc"

for file in "$sch_dir"/*.sch
do
    if [ -f "$file" ]
    then
        filename=${file##*/}
        shortname=${filename%.*}
        gschem -p -o $pdf_dir/$shortname.ps -s $pdf_dir/print.scm $sch_dir/$shortname.sch
        if [ -x /usr/bin/psnup ]
        then
            /usr/bin/psnup -p a3 -l -m -1.20cm $pdf_dir/$shortname.ps $pdf_dir/$shortname-trimmed.ps
        fi
        if [ -x /usr/bin/ps2pdf14  ]
        then
            /usr/bin/ps2pdf14 -sPAPERSIZE=a3 $pdf_dir/$shortname-trimmed.ps $pdf_dir/$shortname.pdf
        fi
        if [ -e $pdf_dir/$shortname.ps ]
        then
            rm $pdf_dir/$shortname.ps
        fi
        if [ -e $pdf_dir/$shortname-trimmed.ps ]
        then
            rm $pdf_dir/$shortname-trimmed.ps
        fi
        if [ -e $pdf_dir/$shortname.pdf ]
        then
            pdf_query+=("$pdf_dir/$shortname.pdf")

        fi
    fi
done

if [ -n "$pdf_query" ]
then
    if [ -x /usr/bin/pdftk ]
    then
        /usr/bin/pdftk "${pdf_query[@]}" cat output $pdf_dir/$project-schematics.pdf
    fi
fi

exit
