#!/bin/sh

cols="footprint,devmap,bom-pn-lcsc,footprint-todo,devmap-todo"
omit_comps=0
omit_nets=0

# gets an abstract model on its stdin
abst2tsv()
{
	awk -v "cols=$cols" -v "omit_comps=$omit_comps" -v "omit_nets=$omit_nets" '
		BEGIN {
			split(cols, COL, "[	 ,]+")
		}

		function del_obj() {
			name = ""
			delete ATTR
		}

		# print a row of component using preconfigured attribute keys
		function print_obj(     key,n) {
			if ((name == "") || (name ~ "^anon_comp_[0-9]*") || (name ~ "/anon_comp_[0-9]+$"))
				return

			printf("%s", name)
			for(n = 1; (n in COL); n++) {
				key = COL[n]
				val = ATTR[key]
				if (val == "")
					val = "-"
				printf("\t%s", val)
			}
			printf("\n")

			del_obj()
		}

		# process the components tree (if not omit_comps)
		/^components/     { if (!omit_comps) comps = 1; next }
		/^[^ ]/           { comps = 0; }

		# process the nets tree (if not omit_comps)
		/^nets/           { if (!omit_nets) nets = 1; next }
		/^[^ ]/           { nets = 0; }

		# do not process any other tree
		(!comps && !nets) { next }

		# ignore any object that ismarked for OMIT
		/^  OMIT/         { comps = 0; nets = 0; del_obj(); next }

		# pick up component or network name
		/^ [^ ]/          { name = $1; sub("^ ", "", name); next }

		# process the component/attributes subtree only
		/^  attributes/   { attrs = 1; next }
		/^  [^ ]/         { print_obj(); attrs = 0; next }
		(!attrs)          { next }

		# parse key=value and store result
		{
			key = $0
			val = $0
			sub("=.*", "", key)
			sub("^ *", "", key)
			sub("^[^=]*=", "", val)
			ATTR[key] = val
		}


		END {
			print_obj()
		}
	'
}

help()
{
echo 'sch-rnd-abst2tsv - print the abstract model in a custom TSV format
Syntax: sch-rnd-abst2tsv [--cols a,b,..] [--omit-comps] [--omit-nets] <files>

 --cols a,b,...       comma separated list of ordered attribute names
 --omit-comps         do not print components
 --omit-nets          do not print nets

Each component or network becomes a single row of the output TSV. Columns
of the TSV are specified by cols. When cols is omitted, the following
default is used: '"$cols"'

'
}

# process command line arguments
original_count=$#

# Iterate exactly once through the original set
i=0
while test "$i" -lt "$original_count"
do
	case "$1" in
		--cols) cols=$2; shift 2 ;;
		--omit-comps) omit_comps=1; shift 1;;
		--omit-nets)  omit_nets=1; shift 1;;
		--help)       help; exit 0;;
	*)
		# append anything else to the END of the parameter list.
		arg="$1"
		shift 1
		set -- "$@" "$arg"
	;;
	esac
	i=$((i + 1))
done

# now $@ contains only arguments we did not remove; run the export on it

tmp=.sch-fptool.tmp
touch $tmp && rm $tmp && sch-rnd -x abst "$@" --outfile $tmp && abst2tsv < $tmp
rm $tmp
