#!/bin/bash

# object lookup from NED
# objNED [-v VEROSITY] {-s} {-h} objectname (or from pipe)
# WARNING: This tool accepts only one object at a time

# LAST REVISION: 27-January-2020
#-----------------------------------------------------------------------
HELP=; VERB=1; SHOW=;
#-----------------------------------------------------------------------
TF="OUT_objNED.tmp" TFt=${TF}t
trap "[ -e $TF ] && rm $TF; [ -e $TFt ] && rm $TFt" EXIT
#-----------------------------------------------------------------------

while getopts v:sh OPTVAL
do
    case $OPTVAL in
	h) HELP=1;;
	s) SHOW=1;;
	v) VERB=$OPTARG;;
	*) echo "objNED -h for help"; exit -1;;
    esac
done
shift $((OPTIND-1))

if [ $HELP ]; then
  echo -e "\n\tobjNED [-v VERBOSITY ] {-h} objectname1 objectname2 .. (or pipe)"
  echo -e "\tgiven Object Name (quoted) eturns summary from NED"
  echo -e "\t-s .. show the data as keyword:value, one per line"
  echo -e "\t-v .. VERBOSITY [1]:  RA, DEC, Name, Type, z"
  echo -e "\tother VERBOSITY to be implemented\n"
  exit
fi

#-----------------------------------------------------------------------
#input from pipe? if so, convert to positional parameters
#-----------------------------------------------------------------------

if [ $# -eq 0 ]; then 
  if [ -p /dev/stdin ]; then
    PIPE=$(cat -)
    set -- $PIPE
  else
    echo "no value supplied via pipe or command line"
    exit -1
  fi
fi

#-----------------------------------------------------------------------
# the heavy lift!
#-----------------------------------------------------------------------

while [ $# -ge 1 ]
do
    OBJNAME=$1; shift

    curl -s -X POST --data 'json={"name":{"v":"'"$OBJNAME"'"}}' https://ned.ipac.caltech.edu/srs/ObjectLookup -o $TF

    HDR="RA DEC Name Type Redshift"

    if [ $SHOW ]; then 
	jq '.Preferred | .Position.RA,.Position.Dec,.Name,.ObjType.Value,.Redshift.Value' $TF > $TFt
  	paste <(echo $HDR | xargs -n1) $TFt
    else
  	jq '.Preferred | .Position.RA,.Position.Dec,.Name,.ObjType.Value,.Redshift.Value' $TF | paste -s -
    fi

done