#!/bin/bash

ns=$(oc project -q)

oc create -f - <<EOF
---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: decitasker
  labels:
    k8s-app: decitasker-server
spec:
  replicas: 1
  selector:
    matchLabels:
      k8s-app: decitasker-server
  template:
    metadata:
      labels:
        k8s-app: decitasker-server
    spec:
      containers:
      - name: vertical-pod-autoscaler-operator
        image: quay.io/joelsmith/decitasker
        command:
        - /decitasker
        ports:
        - containerPort: 8080
        resources:
          requests:
            cpu: 20m
            memory: 50Mi
      restartPolicy: Always
---
apiVersion: v1
kind: Service
metadata:
  name: decitasker
  labels:
    k8s-app: decitasker-server
spec:
  ports:
  - name: 8080-tcp
    port: 8080
    protocol: TCP
    targetPort: 8080
  selector:
    k8s-app: decitasker-server
  sessionAffinity: None
  type: ClusterIP
---
apiVersion: route.openshift.io/v1
kind: Route
metadata:
  labels:
    k8s-app: decitasker
  name: decitasker
spec:
  tls:
    insecureEdgeTerminationPolicy: Redirect
    termination: edge
  to:
    kind: Service
    name: decitasker
---
apiVersion: v1
kind: ServiceAccount
metadata:
  name: thanos
---
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
  name: thanos-metrics-reader
rules:
- apiGroups:
  - ""
  resources:
  - pods
  verbs:
  - get
- apiGroups:
  - metrics.k8s.io
  resources:
  - pods
  - nodes
  verbs:
  - get
  - list
  - watch
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
  name: thanos-metrics-reader-$ns
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: ClusterRole
  name: thanos-metrics-reader
subjects:
- kind: ServiceAccount
  name: thanos
  namespace: $ns
EOF

oc adm policy add-cluster-role-to-user cluster-monitoring-view -z thanos                                                                                

token=$(oc get serviceaccount thanos -o json | jq -r '[ .secrets[] | select(.name | startswith("thanos-token")) | .name ] | first')

sed "s/thanos-token$/$token/" <<EOF | oc create -f -
---
apiVersion: keda.sh/v1alpha1
kind: TriggerAuthentication
metadata:
  name: decitasker
spec:
  podIdentity:
    provider: none
  secretTargetRef:
  - parameter: bearerToken
    name: thanos-token
    key: token
  - parameter: ca
    name: thanos-token
    key: ca.crt
EOF

oc create -f - <<EOF
---
apiVersion: keda.sh/v1alpha1
kind: ScaledObject
metadata:
  name: decitasker
spec:
  scaleTargetRef:
    name: decitasker
  minReplicaCount: 1
  maxReplicaCount: 10
  triggers:
  - type: prometheus 
    authenticationRef:
      name: decitasker
    metadata:
      serverAddress: https://thanos-querier.openshift-monitoring.svc.cluster.local:9091
      metricName: http_requests_total 
      threshold: "5"
      query: sum(rate(haproxy_backend_http_responses_total{exported_namespace="$ns",route="decitasker"}[2m]))
      authModes: bearer
EOF
