#!/bin/bash -e

script_dir=$(cd $(dirname $0); pwd)

####################
# VARIABLES
####################
ATHENA_CATALOG=AwsDataCatalog
ENVS=(trial staging production)
DEFAULT_AWS_PROFILE=hoge

####################
# functions
####################
containsElement () {
  local e match="$1"
  shift
  for e; do [[ "$e" == "$match" ]] && return; done
  echo "n"
}

####################
# usage
####################
cmdname=`basename $0`
function usage()
{
  echo "Usage: ${cmdname} env [OPTIONS]"
  echo ""
  echo "env: ${ENVS[@]}"
  echo "OPTIONS:"
  echo "  --profile name, aws profile, default '$DEFAULT_AWS_PROFILE'."
  echo ""
  exit 1
}

if [[ $# == 0 ]]; then
  usage
fi

while (( $# > 0 ))
do
  case "$1" in
    -*)
      if [[ "$1" =~ '--help' ]]; then
        usage
      fi
      if [[ "$1" =~ '--profile' ]]; then
        shift
        if [[ $# == 0 ]]; then
          usage
        fi
        aws_profile=$1
        shift
      fi
      ;;
    *)
      ((++argc))
      argv=("${argv[@]}" "$1")
      shift
      ;;
  esac
done

environment=${argv[0]}
if [[ $(containsElement $environment "${ENVS[@]}") == "n" ]]; then
  usage
fi

if [[ $aws_profile == "" ]]; then
  aws_profile=$DEFAULT_AWS_PROFILE
fi

tables_metadata=$(aws athena list-table-metadata --catalog-name=$ATHENA_CATALOG --database-name=platform_kpi_log_$environment --profile $aws_profile)
created_tables=$(echo $tables_metadata | jq -r '.TableMetadataList[] | .Name | @sh')

output="テーブル\t存在"
for filename in `ls ./tables`; do
  table="${filename%.*}"
  existable='×'
  for t in ${created_tables[@]}; do
    if [[ $t == "'$table'" ]]; then
      existable='○'
    fi
  done

  output="$output\n$(echo -e "$table \t $existable\n")"
done

echo -e $output | column -t