#!/bin/bash
#### USAGE:
 
## cs_cloner.sh <source domain> <dest domain> <region, optional. will try your CLI's configured default domain.>
 
## Requires the AWS CLI to be configured, as it will make calls using the CLI itself.
 
srcdomain=$1
destdomain=$2
region=$3
 
src_qry="aws cloudsearch describe-index-fields --domain-name $srcdomain --output json"
 
if [[ $region && ${region-x} ]]; then
  src_qry=$src_qry" --region $region"
fi
 
fields=`eval $src_qry | jq .IndexFields`
 
num_fields=`echo $fields | jq  '. | length'`
 
i=0
until [ $i == $num_fields ]; do
  field=`echo $fields | jq ".[$i]"`
  field_name=`echo $field | jq -r '.Options.IndexFieldName'`
  field_type=`echo $field | jq -r '.Options.IndexFieldType'`
  case "$field_type" in
    text)
      opts=TextOptions
      ;;
    text-array)
      opts=TextArrayOptions
      ;;
    date)
      opts=DateOptions
      ;;
    date-array)
      opts=DateArrayOptions
      ;;
    double)
      opts=DoubleOptions
      ;;
    double-array)
      opts=DoubleArrayOptions
      ;;
    literal)
      opts=LiteralOptions
      ;;
    literal-array)
      opts=LiteralArrayOptions
      ;;
    int)
      opts=IntOptions
      ;;
    int-array)
      opts=IntArrayOptions
      ;;
    latlon)
      opts=LatLonOptions
      ;;
  esac
 
  field_sort=`echo $field | jq -r ".Options.$opts.SortEnabled"`
  field_facet=`echo $field | jq -r ".Options.$opts.FacetEnabled"`
  field_search=`echo $field | jq -r ".Options.$opts.SearchEnabled"`
  field_return=`echo $field | jq -r ".Options.$opts.ReturnEnabled"`
  field_highlight=`echo $field | jq -r ".Options.$opts.HighlightEnabled"`
  field_scheme=`echo $field | jq -r ".Options.$opts.AnalysisScheme"`
  field_default_value=`echo $field | jq -r ".Options.$opts.DefaultValue"`
 
  str="aws cloudsearch define-index-field --domain-name $destdomain --name $field_name --type $field_type"
 
  if [ $field_sort != 'null' ]; then
    str=$str" --sort-enabled $field_sort"
  fi
 
  if [ $field_facet != 'null' ]; then
    str=$str" --facet-enabled $field_facet"
  fi
 
  if [ $field_search != 'null' ]; then
    str=$str" --search-enabled $field_search"
  fi
 
  if [ $field_return != 'null' ]; then
    str=$str" --return-enabled $field_return"
  fi
 
  if [ $field_highlight != 'null' ]; then
    str=$str" --highlight-enabled $field_highlight"
  fi
 
  if [ $field_scheme != 'null' ]; then
    str=$str" --analysis-scheme $field_scheme"
  fi
 
  if [ $field_default_value != 'null' ]; then
    str=$str" --default-value $field_default_value"
  fi
 
  if [[ $region && ${region-x} ]]; then
    str=$str" --region $region"
  fi
 
  eval $str
  let i+=1
done
