#!/usr/bin/mawk -We
# =====================================================================
# csa-keypath: print the path to the file containing a given key in a
#	       PBC tree.
#
# Copyright (c) 2003,2007 Carlo Strozzi
#
# 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; version 2 dated June, 1991.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
#
# =====================================================================

BEGIN {

  # Get local settings.
   csa_install = ENVIRON["CSA_INSTALL"]
   stdout = ENVIRON["CSA_STDOUT"]
   stderr = ENVIRON["CSA_STDERR"]

   # Set default values if necessary.
   if (csa_install == NULL) csa_install = "/usr/local/csa"
   if (stdout == NULL) stdout = "/dev/stdout"
   if (stderr == NULL) stderr = "/dev/stderr"

   if (ARGC != 3) {
      print "usage: keypath value specs" > stderr
      exit(1)
   }

   if (ARGV[1] !~ /^[-_a-zA-Z0-9@.]+$/) {
      print "keypath: invalid key value" > stderr
      exit(1)
   }

   key = ARGV[1]

   # Check PBC specs.
   if (ARGV[2] !~ /^-*[1-9,\/]+$/) {
      print "keypath: bad key specs syntax" > stderr
      exit(1)
   }

   specs = ARGV[2]

   # In case in the future the PBC specs will be read from a schema table.
   sub(/^-+\/?/,"",specs)

   split(specs,a,"/")

   while (a[++i] != "") {
      if (split(a[i],b,",") != 2) {
	 print "keypath: invalid key specs" > stderr
	 exit(1)
      }
      k = substr(key,b[1],b[2])
      while (length(k) < b[2]) k = k "?"	# pad with wildcards
      pbc = pbc "/" k
   }

   sub(/^\//,"",pbc)				# strip leading slash

   print pbc
}

# =====================================================================
# end of keypath
# =====================================================================
