#!/bin/sh

# display help
help() {
	case $1 in
		gschem|sch)
			echo "$prg $1 file - edit schematics using gschem."
			;;
		pcb)
			echo "$prg $1 file - edit pcb layout using pcb"
			;;
		gattrib|attrib)
			echo "$prg $1 file - edit attributes of a schematics using gattrib."
			;;
		xgsch2pcb|project)
			echo "$prg $1 file - edit a project (schematics and pcb) using xgsch2pcb."
			;;
		e|edit)
			echo "$prg $1 file - edit a file with the corresponding tool"
			;;
		*) 
			echo "$prg command [args]
Available commands:
	help [command] - print help about a command
	sch <file>     - edit schematic file (alias: gschem)
	attrib <file>  - edit schematic attributes (alias: gattrib)
	project <file> - edit a project using xgsch2pcb (alias: xgsch2pcb)
	edit <file>    - determine file type and open it (alias: e)
"
	esac
}

# determine the type of the file (using content, not file name)
type() {
	awk '
		# .pcb is the easiest to find out, lets try that first (in the first 4 lines)
		/^# release:.*pcb/ {
			if (RN < 4) {
				print "pcb"
				found=1
				exit
			}	
		}
		# .sch is harder - lets assume the first line is the v line (in the first 4 lines)
		/^v [0-9]* [0-9]*/ {
			if (RN < 4) {
				print "sch"
				found=1
				exit
			}
		}
		# (x)gsch2pcb project files should contain schematics and output-name
		/^schematics |output-name / {
			project++
			if (project > 1) {
				print "gsch2pcb"
				found=1
				exit
			}
		}

		END {
			if (found != 1)
				print "UNKNOWN"
		}
	' < $1
}

# edit a file choosing the proper tool
edit() {
	if test -z "$1"
	then
		echo "Need a file name to edit"
	fi
	
	if ! test -f "$1"
	then
		echo "No such file '$1'"
		exit 1
	fi
	file_type=`type $1`
	case $file_type in
		sch) geda gschem $1 ;;
		pcb) geda pcb $1 ;;
		gsch2pcb) xgsch2pcb pcb $1 ;;
		*)
			echo "Can't edit $1 (type is $file_type)"
			exit
	esac
}

# process command line arguments - besides the main part, edit() will call this back
geda() {
	if test -z $1
	then
		cmd="help"
	else
		cmd=$1
		shift 1
	fi

	case $cmd in
		help) help "$@" ;;
		gschem|sch) gschem "$@" ;;
		pcb) pcb "$@" ;;
		gattrib|attrib) gattrib "$@" ;;
		xgsch2pcb|project) xgsch2pcb "$@" ;;
		e|edit) edit "$@" ;;
		type) type "$@" ;;
		*) echo "unknown argument $cmd - try $prg help"
	esac
}

# -------- main: save the name of the script and run the argument parser ------
prg=$0
geda "$@"

