#!/usr/bin/env bash

# Usage: ./yamlgenerator.sh tag origin_file
# The name of target file will be: tag.yaml 

set -e

tag="$1"
file="$2"
yamltemplate="/tmp/yamltemplate"
outputfile="${tag}.yaml"
swap_file="/tmp/swap_file_for_generator"

cat > "$yamltemplate" <<EOF
apiVersion: apps/v1
kind: Deployment
metadata:
  name: PLACEHOLDER
  namespace: prod
  labels:
    app: PLACEHOLDER
spec:
  replicas: 1
  selector:
    matchLabels:
      app: PLACEHOLDER
  template:
    metadata:
      labels:
        app: PLACEHOLDER
    spec:
      containers:
      - name: mysql-client
        image: widdpim/mysql-client
        # command: ["tail", "-f", "/dev/null"] # debug
        command: ["/usr/bin/bash", "/usr/local/bin/alert.sh"]
        volumeMounts:
        - name: my-secret
          mountPath: /root
        - name: script
          mountPath: /usr/local/bin
      volumes:
      - name: my-secret
        secret:
          secretName: my-cnf-secret
          items:
          - key: mycnf
            path: .my.cnf
      - name: script
        configMap:
          name: PLACEHOLDER-script
---
apiVersion: v1
kind: ConfigMap
metadata:
  name: PLACEHOLDER-script
  namespace: prod
data:
  alert.sh: |
EOF

cat "$yamltemplate" | sed "s/PLACEHOLDER/${tag}/g" > "$outputfile"

cat "$file" | sed 's/^/    /' >> "$outputfile"

if [ "$tag" == "poc-monitor" ]
then
 sed 's/scope="test"/scope="poc"/' "$outputfile" > "$swap_file"
 cat "$swap_file" > "$outputfile"
elif [ "$tag" == "ondemand-monitor" ]
then
 sed 's/scope="test"/scope="ondemand"/' "$outputfile" > "$swap_file"
 cat "$swap_file" > "$outputfile"
elif [ "$tag" == "devtier-monitor" ]
then
 sed 's/scope="test"/scope="devtier"/' "$outputfile" > "$swap_file"
 cat "$swap_file" > "$outputfile"
elif [ "$tag" == "dw-monitor" ]
then
 sed 's/scope="test"/scope="prod"/' "$outputfile" > "$swap_file"
 cat "$swap_file" > "$outputfile"
elif [ "$tag" == "doc-updater" ]
then
 sed 's/scope="test"/scope="prod"/' "$outputfile" > "$swap_file"
 cat "$swap_file" > "$outputfile"
fi

rm "$yamltemplate"
