#!/usr/bin/env ruby

##################################################
#=gpattr
#
# create or overwrite the attributes of a variable specified by
# a gtool4-type URL.
#
#   2005/01/07  D Tsukahara
#
#==USAGE
#
#     % gpattr url
#
# where the format of the url is
#
#     path@varname:var_attr or path@varname+global_attr
#
#==EXAMPLES
#
#    % gpattr data.nc@temp:units=W/m
#    % gpattr data.nc@temp+title="surface temperature"
#    % gpattr --delete data.nc@temp:valid_range
#
##################################################
require "getopts"
require "numru/netcdf"
include NumRu

#####################################################
URLfmt = "path@[varname:var_attr=...][varname|+global_attr]"

def parse_gturl_for_attr(gturl)
  if /(.*)@(.*)/ =~ gturl
    file = $1
    var = $2
  else
    raise "invalid URL: '@' between path & variable is not found" +
      "URL format: " + URLfmt
  end
  if /(.*):(.*)/ =~ var
    var_name = var.split(":")[0]
    att =      var.split(":")[1]
    if /(.*)\=(.*)/ =~ att
      var_att =    att.split("=")[0]
      global_att = nil
      att_val  =   var.split("=")[1]
    elsif ( $OPT_delete || $OPT_d )
      var_att =    att
      global_att = nil
      att_val =    nil
    else
      raise "invalid URL: '=' between atribute name & value is not found\n\n" +
	"URL format: " + URLfmt
    end
  elsif /(.*)\+(.*)/ =~ var
    var_name = var.split("+")[0]
    att =      var.split("+")[1]
    if /(.*)\=(.*)/ =~ att
      var_att =    nil
      global_att = att.split("=")[0]
      att_val =    att.split("=")[1]
    elsif ( $OPT_delete || $OPT_d )
      var_att =    nil
      global_att = att
      att_val =    nil
    else
      raise "invalid URL: '=' between atribute name & value is not found\n\n" +
	"URL format: " + URLfmt
    end
  else
    raise "invalid URL: ':' or '+' between atribute name & value is not found\n\n" +
      "URL format: " + URLfmt
  end
  unless  att_val or ( !($OPT_delete) || !($OPT_d) )
    raise "invalid URL: atribute value is not found. you must point out unless delete attribute\n\n" +
      "URL format: " + URLfmt
  end
  [file, var_name, var_att, global_att, att_val]
end
#####################################################

unless getopts(
               "hd", "help", "delete"
               )
  print "#{$0}:illegal options. please exec this program with -h/--help. \n"
  exit 1
end

usage = "\n\nUSAGE:\n\n % " + $0 + " " + URLfmt + "\n"

raise usage if ARGV.length != 1 or /^-+h/ =~ ARGV[0]
gturl = ARGV[0]
file, var, var_att, global_att, att_val = parse_gturl_for_attr(gturl)



nc =  NetCDF.new(file, "a+")
nc.redef
if ( $OPT_d || $OPT_delete )
  nc.att(global_att).delete               if global_att	
  nc.var(var).att(var_att).delete         if var_att
else
  nc.put_att(global_att, att_val)         if global_att
  nc.var(var).put_att(var_att, att_val)   if var_att
end
nc.close
