#!/bin/sh
#
# gitsch2ps - Generate PS files for KiCad schematics in git
#
# Written 2010 by Werner Almesberger
# Copyright 2010 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()
{
    cat <<EOF 1>&2
usage: $0 [options] top-dir top-schem [commit] outdir

  -c  keep .lib.cache (default: delete it)
  -k  keep the temporary directory and print its name
  -D  debug mode: make temporary work tree unique and keep it
  -S  sanitize the KiCad profile and the top-level sheet
EOF
    exit 1
}


sanitize_profile=true
sanitize_schem=true
keep=false
cache=false
debug=false

while true; do
    case "$1" in
    -c)	cache=true
	shift;;
    -k) keep=true
	shift;;
    -D)	debug=true;
	shift;;
    -S) sanitize_profile=`PATH="$PATH":\`dirname "$0"\` which sanitize-profile`
	[ "$sanitize_profile" = "${sanitize_profile#/}" ] &&
	    sanitize_profile=`pwd`/"$sanitize_profile"
	sanitize_schem=`PATH="$PATH":\`dirname "$0"\` which sanitize-schem`
	[ "$sanitize_schem" = "${sanitize_schem#/}" ] &&
	    sanitize_schem=`pwd`/"$sanitize_schem"
	shift;;
    -*)
	usage;;
    *)
	break;;
    esac
done

[ ! -z "$3" -a -z "$5" ] || usage
dir=$1
schem=$2
sdir=`dirname "$schem"`
if [ -z "$4" ]; then
    commit=HEAD
    outdir=$3
else
    commit=$3
    outdir=$4
fi

[ "$dir" != "${dir#/}" ] || dir=`pwd`/$dir

[ "$commit" != HEAD -o -f "$dir/$schem" ] || usage
[ -d "$dir/.git" ] || usage

if $debug; then
    tmp=$dir/../_gitsch2ps_$commit
else
    tmp=$dir/../_gitsch2ps
fi
sch=$tmp/$sdir

rm -rf "$tmp"
rm -rf "$outdir"

git clone -q -s -n "$dir/.git" "$tmp" || exit
( cd "$tmp" && git checkout -q "$commit"; ) || exit

clib=${schem%.sch}.cache.lib
if [ -e "$tmp/$clib" ]; then
    if $cache; then
	echo "found $clib (keeping it)" 1>&2
    else
	echo "removing $clib" 1>&2
	rm -f "$tmp/$clib"
    fi
fi

pro=${schem%.sch}.pro

if [ ! -f "$tmp/$pro" -a ! -f "$tmp/$schem" ]; then
    echo "neither $pro nor $schem found (checked out into $tmp)" 1>&2
    exit 1
fi

if [ ! -f "$tmp/$schem" ]; then
    echo "$schem not found (checked out into $tmp), skipping commit" 1>&2
    exit 0
fi

if [ ! -f "$tmp/$pro" ]; then
    echo "$pro not found (checked out into $tmp), skipping commit" 1>&2
    exit 0
fi

(
    cd "$sch" || exit
    rm -f *.ps
    $sanitize_profile "$tmp/$pro" || exit
    $sanitize_schem "$tmp/$schem" || exit
    eeschema --plot=ps --plot-bw "$tmp/$schem"
) || exit

mkdir -p "$outdir"
if $debug; then
    cp "$sch"/*.ps "$outdir"
else
    mv "$sch"/*.ps "$outdir"
fi

if $keep; then
    echo "$tmp"
else
    $debug || rm -rf "$tmp"
fi