#! /usr/bin/env bash

providers_tf="./providers.tf"
state_backend_tf="./state-backend.tf"
taskfile_yml="./Taskfile.yml"
main_tf="./main.tf"

if [ ! -f "$providers_tf" ]; then
	cat >${providers_tf} <<EOF
terraform {
  required_providers {
    google = {
      source  = "hashicorp/google"
      version = "5.19.0"
    }
  }
}
EOF
fi

if [ ! -f "$state_backend_tf" ]; then
	cat >$state_backend_tf <<EOF
terraform {
  required_version = ">= 1.2.0"

  backend "kubernetes" {
    # read more at https://developer.hashicorp.com/terraform/language/settings/backends/kubernetes#configuration-variables
    secret_suffix = "state"

    # when running on a kubernetes cluster, specify env-vars:
    #   - KUBE_IN_CLUSTER_CONFIG="true"
    #   - KUBE_NAMESPACE="some namespace"

    # when running on local machine, uncomment the following, and pass appropriate values
    # namespace   = "default"
    # config_path = "~/.kube/configs/kloudlite-dev.yml"
  }
}
EOF
fi

bundle=$(fd '' ../../../terraform/bundles -t d | fzf --prompt="Choose Bundle> ")
if [ -z "$bundle" ]; then
	echo "bundle not choosen" && exit 1
fi

if [ ! -f "$taskfile_yml" ]; then
	cat >$taskfile_yml <<EOTF
version: 3

tasks:
  sync-variables:
    vars:
      bundlePath: "$bundle"
      banner: |+
        /*
        DO NOT EDIT THIS FILE DIRECTLY. IT WILL BE OVERWRITTEN.
        If you need to change any variable, please edit the corresponding variables in the {{.bundlePath}} directory.
        If you want to create new variables, please create them in other files
        */
    cmds:
      - |+ #sh
        bundlePath="{{.bundlePath}}"
        bundleName=\$(basename "\$bundlePath")
        if [ -f "./variables-\$bundleName.tf" ]; then
          chmod 600 "./variables-\$bundleName.tf"
        fi

        [ -d "\$bundlePath" ] || (echo "bundle path does not exist" && exit 1)
        
        cat > "./variables-\$bundleName.tf" <<EOF
        {{.banner}}
        EOF
        
        cat \$bundlePath/variables.tf >> ./variables-\$bundleName.tf
        chmod 400 "./variables-\$bundleName.tf"
EOTF
fi

if [ ! -f "$main_tf" ]; then
	cat >$main_tf <<EOF
  module "$(basename "$bundle")" {
  source = "$bundle"
}
EOF
fi
