#!/bin/bash

########################################################################################
# Program: slc2ca                                                                      #
# Author: S.Alverson                                                                   #
# Created: Jan-22-2015                                                                 #
# Modified: Mar-17-2015, S. Alverson                                                   #
#               - Fixed bug which assumed only two columns for device names            #
#               - Added ability to search for all units using wildcard                 #
#               - Removed "SPARE" channels from device listing                         #
#               - Removed header text and print out indent to allow for inline cagets  #
#                                                                                      #
# Purpose: Find available Channel Access read back PVs for SLC devices                 #
# Usage: slc2ca PRIM MICR UNIT                                                         #
#          PRIM: Primary for device.  ex. QUAD, BPMS, MISC, etc.                       #
#          MICR: Micro (location) for device.  ex. LI12, EP01, CA11, etc.              #
#          UNIT: Device unit number (optional)                                         #
#                                                                                      #
#        ex. slc2ca MISC MC00 561                                                      #
#            slc2ca PPS LI12 *                                                         #
#            slc2ca ASTS LI00                                                          #
#                                                                                      #
########################################################################################

# Check for correct number of inputs and parse
if [ $# -lt 2 ];then
    echo -e "Please enter PRIM, MICR, and UNIT!\nex:   ./slc2ca QUAD LI15 301"
    exit 1
else
    # Convert inputs to all uppercase
    PRIM=$(echo "$1" | tr '[a-z]' '[A-Z]') 
    MICR=$(echo "$2" | tr '[a-z]' '[A-Z]')
    UNIT=$(echo "$3" | tr '[a-z]' '[A-Z]')
fi

unknownDevice(){
    echo "Device does not appear to exist! Check unit number."
    exit 1
}

parseMuxedDigital(){
    if [ "$UNIT" == "" ] || [ "$UNIT" == '*' ]; then
	unitlist=$(aidalist "$PRIM:$MICR:%" |  cut -d\: -f3 | uniq)
    else
	unitlist="$UNIT"
    fi

    for i in $unitlist; do
        #DODN=$(curl -s www-mcc.slac.stanford.edu/ref_dbsfile/DOD_$MICR.DBS | grep -A 2 "$PRIM\:$MICR,$UNIT" | grep UNIT | sed -e 's/^.*= //' -e 's/,.*//')
	DODN=$(caget -t "$MICR:$PRIM:$i:UNIT" | awk '{print $2}')

        # If no entry returned, throw error and exit
	if [ "$DODN" == "" ];then unknownDevice; fi	
   
        # Parse returned data                                                Remove commented lines and extract field for search until reach ">"
	DODN_ENTRY=$(curl -s www-mcc.slac.stanford.edu/ref_dbsfile/DODN.DBS | sed -n -e "/^\!/n;/DODN.*,$DODN;/,/>/p")
	SCNM_TAG=$(echo "$DODN_ENTRY" | sed -n -e "/^\!/n;/SCNM/,/\;/p")
	SCNM_LIST1=$(echo "$SCNM_TAG" | cut -d\" -f2)
	SCNM_LIST2=$(echo "$SCNM_TAG" | cut -d\" -f4)
	
        #echo "PV List:"
	pv=""
	for SECN in $SCNM_LIST1 $SCNM_LIST2; do
	    pv="$pv$MICR:$PRIM:$i:$SECN\n"
	done
	echo -e "$pv" | sort | uniq
    done
}

parseAnalog(){
    # Grab analog database file for area                                       Remove comments and extract device entry up to ">"
    url="www-mcc.slac.stanford.edu/ref_dbsfile/ASTS$MICR.DBS"
    webdata=$(curl -s "$url")
    if [ "$UNIT" == "" ] || [ "$UNIT" == '*' ]; then
	unitlist=$(echo "$webdata" | grep "$PRIM:$MICR," | sed "s/;.*$//g;s/$MICR//g;s/[^0-9]//g")
    else
	unitlist="$UNIT"
    fi
    
    for i in $unitlist; do
	ASTS_ENTRY=$(echo "$webdata" | sed -n -e "/^\!/n;/$MICR,$i;/,/>/p")

        # If no entry returned, throw error and exit
	if [ "$ASTS_ENTRY" == "" ];then unknownDevice; fi
	
        # Parse returned data          Remove commented lines and extract field for search until reach semicolon, 
	NAME_TAG=$(echo "$ASTS_ENTRY" | sed -n -e '/^\!/n;/NAME/,/\;/p' | sed  -e 's/\"/\n/g' | grep "^[^,\n ;<>]" | uniq)
                                                                          # Reform into single column and remove non strings
	
	#NAME_LIST1=$(echo "$NAME_TAG" | cut -d\" -f2)
	#NAME_LIST2=$(echo "$NAME_TAG" | cut -d\" -f4)
	
        #echo "PV List:"
	#for SECN in $NAME_LIST1 $NAME_LIST2; do
	pv=""
	for SECN in $NAME_TAG; do
	    if [ "$SECN" != "SPARE" ];then
		pv="$pv$MICR:$PRIM:$SECN\n"
	    fi
	done
	# Sort PVs and remove duplicates
	echo -e "$pv" | sort | uniq
    done
}

parseDigital(){
    if [ "$PRIM" == "BPMS" ] || [ "$PRIM" == "BPMP" ] ;then 
	FNAME="BPM_" 
    else
	FNAME="$PRIM"
    fi
    if [ "$PRIM" == "FBCK" ];then
	url="www-mcc.slac.stanford.edu/ref_dbsfile/FBCK.DBS" 
    else
	url="www-mcc.slac.stanford.edu/ref_dbsfile/$FNAME$MICR.DBS"
    fi
    webdata=$(curl -s "$url")
    if [ "$UNIT" == "" ] || [ "$UNIT" == '*' ]; then
	unitlist=$(echo "$webdata" | grep -e "$PRIM:$MICR," -e "$PRIM: $MICR," | sed "s/;.*$//g;s/$MICR//g;s/[^0-9]//g")
    else
	unitlist="$UNIT"
    fi
    
    for i in $unitlist; do
        # Grab database file for device type and area                               Remove comments and extract device entry up to ">"
	DEV_ENTRY=$(echo "$webdata" | sed -n -e "/^\!/n;/$PRIM\: *$MICR, *$i;/,/>/p")

        # If no entry returned, throw error and exit
	if [ "$DEV_ENTRY" == "" ];then unknownDevice; fi
    
        # Parse returned data           Remove 1st Line    Extract :SECN:       Remove ":"
	SECN_LIST=$(echo "$DEV_ENTRY" | grep -v ":$PRIM" | grep -Po ':.*?:' | sed -e 's/\://g')

        #echo "PV List:"
	pv=""
	for SECN in $SECN_LIST; do
	    if [ "$SECN" != "SPARE" ];then
		pv="$pv$MICR:$PRIM:$i:$SECN\n"
	    fi
	done
	# Sort PVs and remove duplicates
	echo -e "$pv" | sort | uniq
    done
}

parseFeedback(){
    loopdata=$(curl -s "www-mcc.slac.stanford.edu/ref_dbsfile/FBCK.DBS")
    if [ "$UNIT" == "" ] || [ "$UNIT" == '*' ]; then
	unitlist=$(echo "$loopdata" | grep -e "$PRIM:$MICR," -e "$PRIM: $MICR," | sed "s/;.*$//g;s/$MICR//g;s/[^0-9]//g")
    else
	unitlist="$UNIT"
    fi

    url="www-mcc.slac.stanford.edu/ref_dbsfile/FELB$MICR.DBS"
    for i in $unitlist; do
	loop_name=$(caget -t "$MICR:FBCK:$i:NAME")
	if [ "$loop_name" == "" ]; then unknownDevice;fi

	if [ $loop_name != "SPARE" ];then
	    webdata=$(curl -s "$url")
	    #DEV_ENTRY=$(echo "$webdata") # | sed -n -e "/^\!/n;")
	    #echo "$DEV_ENTRY"
	    ELEM_LIST=$(echo "$webdata" | grep ":NAME:" | sed -e 's/[^"]*"//' -e 's/".*//')
	    #echo "$ELEM_LIST"
	    pv=""
	    for j in $ELEM_LIST;do
		pv="$pv$MICR:$loop_name:$j\n"
	    done
	    echo -e "$pv" | sort | uniq
       fi
    done
}

##################  Program start ###################

# Choose method of name conversion based on Primary
if [ "$PRIM" == "ASTS" ];then
    parseAnalog
elif [ "$PRIM" == "MISC" ] || [ "$PRIM" == "PPS" ] || [ "$PRIM" == "MPS" ] || [ "$PRIM" == "BCS" ] || [ "$PRIM" == "WATR" ];then
    parseMuxedDigital
elif [ "$PRIM" == "FBCK" ];then
    parseDigital
    parseFeedback
else
    parseDigital
fi

exit 0