#!/bin/bash

#set -x

# Get search entry from CLI args
QUERY=$@

# Get auth token (seems to be unnecessary - but just in case, match what the website does)
TOKENURL="https://www.belden.com/coveo/rest/token?t="$(date +%s)
TOKEN=$(curl "$TOKENURL" 2>/dev/null | jq -r ".token")

# Coveo search URL
SEARCHURL="https://www.belden.com/coveo/rest/search"


#SEARCHDATA='{ \"q\": \"$QUERY\", \"searchHub\": \"products-only-search\", \"aq\": \"(NOT @z95xtemplate==(ADB6CA4F03EF4F47B9AC9CE2BA53FF97,FE5DD82648C6436DB87A7C4210C7413B)) ((@syssource==\"website_001002_catalog_index-rg-nc-prod-sitecore-prod\" @catalogitemprimarycategorypublished==true)) ((@catalogitemregionavailable=Global) (@z95xlanguage==en))\", \"cq\": \"((@z95xlanguage==en) (@z95xlatestversion==1) (@source==\"Coveo_web_index - rg-nc-prod-sitecore-prod\")) OR (@source==(\"website_001002_catalog_index-rg-nc-prod-sitecore-prod\",\"website_001002_Category_index-rg-nc-prod-sitecore-prod\"))\", \"firstResult\": \"0\" }'
#SEARCHDATA='{ "q": "'$QUERY'", "numberOfResults": "25", "sortCriteria": "@catalogitemwebdisplaypriority ascending", "searchHub": "products-only-search", "pipeline": "Site Search", "maximumAge": "900000", "tab": "products-search", "locale": "en", "aq": "(NOT @z95xtemplate==(ADB6CA4F03EF4F47B9AC9CE2BA53FF97,FE5DD82648C6436DB87A7C4210C7413B)) ((@syssource==\"website_001002_catalog_index-rg-nc-prod-sitecore-prod\" @catalogitemprimarycategorypublished==true)) ((@catalogitemregionavailable=Global) (@z95xlanguage==en))", "cq": "((@z95xlanguage==en) (@z95xlatestversion==1) (@source==\"Coveo_web_index - rg-nc-prod-sitecore-prod\")) OR (@source==(\"website_001002_catalog_index-rg-nc-prod-sitecore-prod\",\"website_001002_Category_index-rg-nc-prod-sitecore-prod\"))", "firstResult": "0" }'

# Query data - includes the default filter, sort, etc options used by the website search
#SEARCHDATA='{ "q": "'$QUERY'", "sortCriteria": "relevancy", "numberOfResults": "25", "sortCriteria": "@catalogitemwebdisplaypriority ascending", "searchHub": "products-only-search", "pipeline": "Site Search", "maximumAge": "900000", "tab": "products-search", "locale": "en", "aq": "(NOT @z95xtemplate==(ADB6CA4F03EF4F47B9AC9CE2BA53FF97,FE5DD82648C6436DB87A7C4210C7413B)) ((@syssource==\"website_001002_catalog_index-rg-nc-prod-sitecore-prod\" @catalogitemprimarycategorypublished==true)) ((@catalogitemregionavailable=Global) (@z95xlanguage==en))", "cq": "((@z95xlanguage==en) (@z95xlatestversion==1) (@source==\"Coveo_web_index - rg-nc-prod-sitecore-prod\")) OR (@source==(\"website_001002_catalog_index-rg-nc-prod-sitecore-prod\",\"website_001002_Category_index-rg-nc-prod-sitecore-prod\"))", "firstResult": "0" }, "categoryFacets": "[{\"field\":\"@catalogitemcategories\",\"path\":[],\"injectionDepth\":1000,\"maximumNumberOfValues\":6,\"delimitingCharacter\":\"|\"}]", "facetOptions": "{}" }'
SEARCHDATA='{ "q": "'$QUERY'", "sortCriteria": "relevancy", "numberOfResults": "250", "sortCriteria": "@catalogitemwebdisplaypriority ascending", "searchHub": "products-only-search", "pipeline": "Site Search", "maximumAge": "900000", "tab": "products-search", "locale": "en", "aq": "(NOT @z95xtemplate==(ADB6CA4F03EF4F47B9AC9CE2BA53FF97,FE5DD82648C6436DB87A7C4210C7413B)) ((@syssource==\"website_001002_catalog_index-rg-nc-prod-sitecore-prod\" @catalogitemprimarycategorypublished==true)) ((@catalogitemregionavailable=Global) (@z95xlanguage==en))", "cq": "((@z95xlanguage==en) (@z95xlatestversion==1) (@source==\"Coveo_web_index - rg-nc-prod-sitecore-prod\")) OR (@source==(\"website_001002_catalog_index-rg-nc-prod-sitecore-prod\",\"website_001002_Category_index-rg-nc-prod-sitecore-prod\"))", "firstResult": "0" }, "categoryFacets": "[{\"field\":\"@catalogitemcategories\",\"path\":[],\"injectionDepth\":1000,\"maximumNumberOfValues\":6,\"delimitingCharacter\":\"|\"}]", "facetOptions": "{}", "groupBy": "    [{\"field\":\"@contenttype\",\"maximumNumberOfValues\":6,\"sortCriteria\":\"occurrences\",\"injectionDepth\":1000,\"completeFacetWithStandardValues\":true,\"allowedValues\":[\"Products\"],\"queryOverride\":\"'$QUERY'\",\"advancedQueryOverride\":\"(NOT @z95xtemplate==(ADB6CA4F03EF4F47B9AC9CE2BA53FF97,FE5DD82648C6436DB87A7C4210C7413B)) ((((((((@z95xpath=3324AF2D58F64C0FB725521052F679D2 @z95xid<>3324AF2D58F64C0FB725521052F679D2) ((@z95xpath=C292F3A37B3A4E6BAB345DF87ADDE516 @z95xid<>C292F3A37B3A4E6BAB345DF87ADDE516) @z95xtemplate==E4EFEB787BDC4B1A908EFC64D56CB2A4)) OR ((@z95xpath=723501A864754FEEB8AE377E4C710271 @z95xid<>723501A864754FEEB8AE377E4C710271) ((@z95xpath=600114EAB0E5407A84AAA9F0985B6575 @z95xid<>600114EAB0E5407A84AAA9F0985B6575) @z95xtemplate==2BE4FD6B3B2C49EBBD9E1F6C92238B05))) OR (@syssource==\\"website_001002_catalog_index-rg-nc-prod-sitecore-prod\\" @catalogitemprimarycategorypublished==true)) OR ((@z95xpath=3324AF2D58F64C0FB725521052F679D2 @z95xid<>3324AF2D58F64C0FB725521052F679D2) @z95xpath<>C292F3A37B3A4E6BAB345DF87ADDE516)) OR @syssource==\\"website_001002_Category_index-rg-nc-prod-sitecore-prod\\") NOT @z95xtemplate==(ADB6CA4F03EF4F47B9AC9CE2BA53FF97,FE5DD82648C6436DB87A7C4210C7413B))) ((@catalogitemregionavailable=Global) (@z95xlanguage==en) OR (@contenttype=(Blogs,Resources,Other)) (NOT @ez120xcludefromcoveo==1))\",\"constantQueryOverride\":\"((@z95xlanguage==en) (@z95xlatestversion==1) (@source==\\"Coveo_web_index - rg-nc-prod-sitecore-prod\\")) OR (@source==(\\"website_001002_catalog_index-rg-nc-prod-sitecore-prod\\",\\"website_001002_Category_index-rg-nc-prod-sitecore-prod\\"))\"},{\"field\":\"@catalogitembrand\",\"maximumNumberOfValues\":6,\"sortCriteria\":\"occurrences\",\"injectionDepth\":1000,\"completeFacetWithStandardValues\":true,\"allowedValues\":[]},{\"field\":\"@catalogitemenvironment\",\"maximumNumberOfValues\":6,\"sortCriteria\":\"occurrences\",\"injectionDepth\":1000,\"completeFacetWithStandardValues\":true,\"allowedValues\":[]},{\"field\":\"@catalogitemregionalavailability\",\"maximumNumberOfValues\":6,\"sortCriteria\":\"occurrences\",\"injectionDepth\":1000,\"completeFacetWithStandardValues\":true,\"allowedValues\":[]},{\"field\":\"@prez45xtez120xt\",\"maximumNumberOfValues\":5,\"sortCriteria\":\"occurrences\",\"injectionDepth\":1000,\"completeFacetWithStandardValues\":true,\"allowedValues\":[]},{\"field\":\"@tags\",\"maximumNumberOfValues\":4,\"sortCriteria\":\"occurrences\",\"injectionDepth\":1000,\"completeFacetWithStandardValues\":true,\"allowedValues\":[]},{\"field\":\"@facetassettype\",\"maximumNumberOfValues\":3,\"sortCriteria\":\"occurrences\",\"injectionDepth\":1000,\"completeFacetWithStandardValues\":true,\"allowedValues\":[]},{\"field\":\"@facetbrand\",\"maximumNumberOfValues\":3,\"sortCriteria\":\"occurrences\",\"injectionDepth\":1000,\"completeFacetWithStandardValues\":true,\"allowedValues\":[]},{\"field\":\"@facetmarket\",\"maximumNumberOfValues\":6,\"sortCriteria\":\"occurrences\",\"injectionDepth\":1000,\"completeFacetWithStandardValues\":true,\"allowedValues\":[]},{\"field\":\"@facetsolution\",\"maximumNumberOfValues\":6,\"sortCriteria\":\"occurrences\",\"injectionDepth\":1000,\"completeFacetWithStandardValues\":true,\"allowedValues\":[]},{\"field\":\"@facetsearchcontentpagetype\",\"maximumNumberOfValues\":6,\"sortCriteria\":\"occurrences\",\"injectionDepth\":1000,\"completeFacetWithStandardValues\":true,\"allowedValues\":[]}]" }'

#SEARCHDATA='{ "q": "LioN-X" }'
#echo $SEARCHDATA

#echo curl \"$SEARCHURL\" $SEARCHOPTS -d "$SEARCHDATA"

# Query the coveo search API.
RESULTS=$(curl "$SEARCHURL" -H "Content-Type: application/json" -H "Authorization: Bearer $TOKEN" -d "$SEARCHDATA" 2>/dev/null )

# Count number of results
COUNT=$(echo "$RESULTS" | jq ".results | length")
#if [ "$COUNT" -ge "250" ]; then
#	echo "There are 250+ search results."
#else
#	echo "There are" $(echo "$RESULTS" | jq ".results | length") "search results."
#fi
#echo $RESULTS | jq
# Reformat results to simpler json. Includes basic cable specs
#echo "$RESULTS" | jq -C "[ .results.[] | { name: .raw.catalogitemshortdesc, partnum: .title } ]"

LIST=$(echo "$RESULTS" | jq "[ .results.[] | { name: .raw.catalogitemshortdesc, brand: .raw.catalogitembrand, description: .raw.catalogitemlongdesc, application: .raw.catalogitemapplication, partnum: .raw.catalogitempartnumber, friendlypartnum: .title, santitizedpartnum: .raw.catalogitemsanitiz122xedname, usagecategory: .raw.catalogitemfilterproductcategory, category: .raw.catalogitemoriginalcategories, gauge: .raw.catalogitemconductorsiz122xe, voltage: .raw.catalogitemulvoltageratingvoltage1, conductors: .raw.catalogitemconductorcombinedcount, fibercount: .raw.catalogitemfibrecountfiber1, maxtemp: .raw.catalogitemultemprating, temprange: .raw.catalogitemoperatingtemprange, shielding: .raw.catalogitemshielding, producttype: .raw.catalogitemproducttype, material: .raw.catalogitemconductormaterialandstranding, construction: .raw.catalogitemconstructiontype, insulation: .raw.catalogiteminsulationmaterial, jacket: .raw.catalogitemjacket, armor: .raw.catalogitemarmortypeandmaterial, flamerating: .raw.catalogitemflamerating, url: (\"https://www.belden.com/products\" + .raw.clickableuri), datasheet: (\"https://catalog.belden.com/techdata/EN/\" + .raw.catalogitemdatasheetid + \"_techdata.pdf\" ), image: (\"https://www.belden.com\" + .raw.catalogitemimageurl) | split(\"?\")[0] } ]")

NUM=$(echo "$RESULTS" | jq -r "[ .results.[].title] | index(\"$QUERY\")")
if ! [ "$NUM" = "null" ]; then
	echo $LIST | jq -r ".[$NUM]"
	#echo "Result matches exact part number input."
	#echo "Result uncertainty:" $(( $COUNT * 1 ))
	exit 0
else
	NUM=$(echo "$RESULTS" | jq -r "[ .results.[].raw.catalogitemsanitiz122xedname ] | index(\"$QUERY\")")
	if ! [ "$NUM" = "null" ]; then
		echo $LIST | jq -r ".[$NUM]"
		exit 0
		#echo "Result matches exact part number input."
	else
		exit 1
		#echo $LIST | jq ".[0]"
		#echo "Unable to find exact match."
		#echo "Result uncertainty:" $(( $COUNT * 4 ))
	fi
fi

