#!/bin/bash -e
COPYRIGHT='
#
# Copyright (c) 2017 SAP SE or an SAP affiliate company. All rights reserved. This file is licensed under the Apache Software License, v. 2 except as noted otherwise in the LICENSE file
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
'

DIR="$(dirname "$0")"
defs="variables.tf"
inputs=( )

contains()
{
  local i
  local e="$1"
  shift
  for i; do
    if [ "$i" == "$e" ]; then
      return 0
    fi
  done
  return 1
}

print_locals()
{
    for l in "${inputs[@]}"; do
      cat <<EOF
module "$l" {
  source="../defaults"
  optional = true
  values=[ "\${var.$l}","\${lookup(var.versions,"$l","")}", "\${local.$l}" ]
}
EOF
    done
}

lvalue()
{
  echo -n "\"\${module.$1.value}\""
}

print_args()
{
  for l in "${inputs[@]}"; do
    echo "      $l = $(lvalue $l)"
  done
}

print_outputs()
{
  for l in "${inputs[@]}"; do
    cat <<EOF
output "$l" {
  value = $(lvalue $l)
}
EOF
  done
}

get_variables()
{
  for v in $defs; do
    (
      V=
      T=string
      while read a; do
        n="$(grep "variable[[:space:]]" <<< "$a" | sed -e 's/.*"\(.*\)".*/\1/')"
        if [ -n "$n" ]; then
          if [ -n "$V" ]; then
            echo "$V $T"
          fi
          V="$n"
          T=string
        else
          t="$(grep "type[[:space:]]=" <<< "$a" | sed -e 's/.*"\(.*\)".*/\1/')"
          if [ -n "$t" ]; then
            T="$t"
          fi
        fi
      done
      if [ -n "$V" ]; then
        echo "$V $T"
      fi
    ) < "$DIR/$v"
  done

}

for v in $defs; do
  while read n t; do
    case "$t" in
      string) inputs+=( $n );;
      list) echo "list variables not supported" >&2: exit 1;;
      *) echo "invalid variable type '$t' for $n" >&1
         exit 1;;
    esac
  done <<<"$(get_variables)"
done

cat >"$DIR/config.tf" <<EOF
$COPYRIGHT

##############################################################################
# version configuration handling
# pack or unpack version variables
# generated by create.sh based on variables.tf
##############################################################################

#
# specify config map to unpack settings into output
#
variable "versions" {
  type = "map"
  default = { }
}

#
# or specify variables according to variables.tf to
# pack a config map
#

$(print_locals)

#
# always provide a config map value
#

output "versions" {
  value = {
$(print_args)
  }
}

#
# always provide all settings as dedicated output
#
$(print_outputs)
EOF
