#!/bin/bash

###
### GETRFCDRAFTNAME - Get draft name from an rfc number
###
### Version 1.0.0
###
### Written in 2008 by Jari Arkko
### Donated to the public domain.
###
###   1.0.0   Initial version
###
### Usage:
###
###   getrfcdraftname [options] [rfc]nnnn[.txt]
###
###   where options is one of the following:
###
###   --debug
###
###   --prefer-family={IPv4,IPv6}
###
### and the output will be
###  
###   draft-foo-nn.txt
###
### or empty, if no information could be found.
###

###
### Parse arguments
###

DEBUG=0
NOVER=0
PREFFAMILY=IPv6

while [ $# -gt 1 ]
do
  case $1 in
    --debug)
                shift;
                DEBUG=1;;
    --nover)
                shift;
                NOVER=1;;
    --prefer-family=IPv4)
                shift;
                PREFFAMILY=IPv4;;
    --prefer-family=IPv6)
                shift;
                PREFFAMILY=IPv6;;
    *)          echo 'getrfcdraftname: Unrecognized argument ('$1') -- exit' >> /dev/stderr;
                exit 1;;
  esac
done

if [ x$1 = x ]
then
  echo 'getrfcdraftname: No argument given -- exit' >> /dev/stderr;
  exit
else
  arg=`echo $1 | sed 's/rfc//g' | sed 's/[.]txt//g'`
fi

WGETOPTS="--prefer-family="$PREFFAMILY" -q --timeout=20"

###
### Datafile processing subroutine
###

function datafileprocess() {
  inputfile=$1;
  outputfile=$2;

  awk '
BEGIN {
  inentry = 0;
  rfcnum = "";
}
/^ *[<]rfc-entry[>] *$/ {
  inentry = 1;
  rfcnum = "";
  next;
}
/^ *[<]doc-id[>]RFC[0-9]+[<].doc-id[>] *$/ {
  if (inentry) {
     text = $0;
     gsub(/^.*RFC/,"",text);
     gsub(/[<].*$/,"",text);
     rfcnum = text;
     inentry = 0;
  }
  next;
}
/^ .*[<]draft[>]draft-.*[<].draft[>] *$/ {
  if (inentry == 0 && rfcnum != "") {
    text = $0;
    sub(/^.*draft-/,"draft-",text);
    gsub(/[<].*$/,"",text);
    draftname = text ".txt";
    printf("rfc%s.txt:%s\n",rfcnum,draftname);
  }
  inentry = 0;
  rfcnum = "";
  next;
}
/.*/ {
  inentry = 0;
  next;
}
END {
}
  ' < $inputfile > $outputfile
}

###
### Fetch the data source file
###

tmpxml=/tmp/rfc-index.xml
tmpdata=/tmp/rfcdraftmapping.txt
if [ -f $tmpxml -a -f $tmpdata ]
then
  ok=ok
else
  rm -f $tmpxml $tmpdata
  if wget $WGETOPTS -O $tmpxml http://www.rfc-editor.org/rfc/rfc-index.xml
  then
    datafileprocess $tmpxml $tmpdata
  else
    echo 'getrfcdraftname: wget failure -- exit' >> /dev/stderr;
    exit 1
  fi
fi

###
### Find the specific RFC information
###

tmpentry=/tmp/getrfcdraftname.entry
rm -f $tmpentry
if fgrep rfc$arg.txt: $tmpdata > $tmpentry
then
  cut -f2 -d: $tmpentry |
  (if [ $NOVER = 0 ]
   then
     cat
   else
     sed 's/-[0-9][0-9][.]txt//'
   fi)
else
  exit 1
fi
