#!/bin/sh -e
#
# sym2xps - Convert a symbol from a Kicad library to Postscript with expanded
#	    pin types
#
# Copyright 2012 by Werner Almesberger
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#


usage()
{
	echo "usage: $0 library symbol unit tmpdir outfile" 1>&2
	exit 1
}


lib=$1
sym=$2
unit=$3
tmp=$4
out=$5

[ "$lib" ] && [ "$sym" ] && [ "$unit" ] && [ "$tmp" ] && [ "$out" ] || usage

[ -r "$lib" ] || {
	echo "$lib: not found" 1>&2
	exit 1
}

grep "^DEF $sym " "$lib" >/dev/null || {
	echo "\"$sym\" not found in $lib" 1>&2
	exit 1
}

[ "${tmp#/}" = "$tmp" ] && tmp=`pwd`/$tmp
[ "${out#/}" = "$out" ] && out=`pwd`/$out

mkdir "$tmp"

trap "rm -rf '$tmp'" 0

expand-pintype "$lib" "$tmp"/tmp.lib

cat <<EOF >"$tmp"/tmp.pro
[eeschema]
version=1
[eeschema/libraries]
LibName1=./tmp
EOF

X=6000
Y=4000

sed "\@^DEF $sym @,/^ENDDEF/p;d" "$lib" |
  awk '/^F. / { if ($1 == "F0") sub(/"$/, "?\"", $2);
    print substr($1, 1, 1), substr($1, 2, 1), $2,
    $6, '$X'+$3, '$Y'+$4, $5, " 0000", $8, $9 }' >"$tmp"/fx.tmp
#F field_number "text" orientation posX posY size Flags (see below)
#F0 reference posx posy text_size text_orient visibile htext_justify vtext_justify

cat <<EOF >"$tmp"/tmp.sch
EESchema Schematic File Version 2  date Mon Mar 26 09:29:33 2012
LIBS:dummy
EELAYER 43  0
EELAYER END
\$Comp
L X$sym ??
U $unit 1 00000000
P $X $Y
`cat "$tmp"/fx.tmp`
	$unit	$X	$Y
	1	0	0	-1
\$EndComp
\$EndSCHEMATC
EOF

cd "$tmp"
eeschema --plot=ps "$tmp/tmp.sch" 
mv tmp.ps "$out"