# Copyright (c) 2019, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
#
# 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.

apiVersion: v1
kind: ConfigMap
metadata:
  name: jenkins-casc-conf
data:
  global-config.yaml: |-
    credentials:
      system:
        domainCredentials:
          - credentials:
              - usernamePassword:
                  scope: GLOBAL
                  id: github_credentials
                  username: ${GITHUB_USERNAME}
                  password: ${GITHUB_PASSWORD}
    jenkins:
      systemMessage: "Kubernetes CI/CD Pipeline for WSO2 Products"
      securityRealm:
        local:
          allowsSignup: false
          users:
            - id: "{{ .Values.jenkins.username }}"
              password: "{{ .Values.jenkins.password }}"
      authorizationStrategy: loggedInUsersCanDoAnything
    jobs:
      {{- $namespace := .Release.Namespace }}
      {{- $jenkinsBaseImageUpdateCron := .Values.jenkins.jobs.baseImageUpdate.cron }}
      {{- $root := . }}
      {{- range .Values.applications }}
      {{- $application := . }}
      - script: >
          folder("{{ $application.name }}")
      {{- range $index, $image := .images }}
      # Custom Image build
      {{- if or $image.customImage $image.wso2microIntegrator }}
      - script: >
          job("{{ $application.name }}/{{ $image.repository }}-image") {
            description()
            logRotator(10)
            keepDependencies(false)
            disabled(false)
            concurrentBuild(true)
            scm {
                git {
                    remote {
                        name('docker-repo')
                        {{- if $image.wso2microIntegrator }}
                        url('{{ $image.wso2microIntegrator.gitRepository }}')
                        {{- else }}
                        url('{{ $image.customImage.dockerfileGitRepo }}')
                        {{- end }}
                        credentials('github_credentials')
                    }
                }
            }
            {{- if $jenkinsBaseImageUpdateCron }}
            triggers {
              scm('* * * * *')
              cron('{{ $jenkinsBaseImageUpdateCron }}')
            }
            {{- end }}
            steps {
              shell("""

                set +x
                {{- if and (not (eq $root.Values.wso2Username "")) (not (eq $root.Values.wso2Password "")) }}
                docker login docker.wso2.com -u \$WSO2_USERNAME -p \$WSO2_PASSWORD
                {{- end }}
                docker login -u \$REGISTRY_USERNAME -p \$REGISTRY_PASSWORD
                set -x

                REGISTRY_NAME="{{ $root.Values.registry.address }}/{{ $image.organization }}"
                REPOSITORY="{{ $image.repository }}"
                {{- if $image.wso2microIntegrator }}
                BASE_IMAGE="{{ $image.wso2microIntegrator.baseImage }}"
                {{- else }}
                BASE_IMAGE="{{ $image.customImage.baseImage }}"
                {{- end }}
                TAG=`echo \$BASE_IMAGE | cut -d ':' -f 2`

                docker pull \$BASE_IMAGE

                GIT_TAG=`git rev-parse --short HEAD`
                {{- if $image.wso2microIntegrator }}
                {{- if $image.wso2microIntegrator.remoteSynapseTestServer.enabled }}
                mvn clean install -Ddockerfile.base.image=\$BASE_IMAGE \
                -Ddockerfile.tag=\$TAG-\$GIT_TAG \
                -Ddockerfile.repository=\$REGISTRY_NAME/\$REPOSITORY \
                -Ddockerfile.username=\$REGISTRY_USERNAME \
                -Ddockerfile.password=\$REGISTRY_PASSWORD \
                -Ddockerfile.build.pullNewerImage=false \
                -DtestServerType=remote \
                -DtestServerHost={{ $image.wso2microIntegrator.remoteSynapseTestServer.hostname }} \
                -DtestServerPort={{ $image.wso2microIntegrator.remoteSynapseTestServer.port }}
                {{- else }}
                mvn clean install -Ddockerfile.base.image=\$BASE_IMAGE \
                -Ddockerfile.tag=\$TIMESTAMP-\$TAG \
                -Ddockerfile.repository=\$REGISTRY_NAME/\$REPOSITORY \
                -Ddockerfile.username=\$REGISTRY_USERNAME \
                -Ddockerfile.password=\$REGISTRY_PASSWORD \
                -Ddockerfile.build.pullNewerImage=false \
                -Dmaven.test.skip=true
                {{- end }}
                {{- else }}
                sed -i \"s|<BASE>|\$BASE_IMAGE|\" Dockerfile

                set +x
                docker build --build-arg WSO2_USERNAME=\$WSO2_USERNAME --build-arg WSO2_PASSWORD=\$WSO2_PASSWORD -t \$REGISTRY_NAME/\$REPOSITORY:\$TAG-\$GIT_TAG .
                set -x

                docker push \$REGISTRY_NAME/\$REPOSITORY:\$TAG-\$GIT_TAG
                {{- end }}

                docker tag \$REGISTRY_NAME/\$REPOSITORY:\$TAG-\$GIT_TAG \$REGISTRY_NAME/\$REPOSITORY
                docker push \$REGISTRY_NAME/\$REPOSITORY
                """)
            }
          }
      {{- end }}
      # Microgateway image build
      {{- if $image.microgateway }}
      - script: >
          job("{{ $application.name }}/{{ $image.repository }}-image") {
            description()
            logRotator(10)
            keepDependencies(false)
            disabled(false)
            concurrentBuild(true)
            scm {
                git {
                    remote {
                        name('docker-repo')
                        url('{{ $image.microgateway.gitRepository }}')
                        credentials('github_credentials')
                    }
                    extensions {
                      wipeOutWorkspace()
                      relativeTargetDirectory('{{ $image.microgateway.projectName }}')
                    }
                }
            }
            triggers {
              scm('* * * * *')
            }
            steps {
              shell("""
                timestamp() {
                  date +\"%Y%m%d%H%M%S\"
                }

                TAG=`cat {{ $image.microgateway.projectName }}/conf/deployment-config.toml | grep "tag" | awk '{print \\\$3}' | sed "s/'//g"`

                sed -i 's|\$MICROGW_TOOLKIT_HOME|/wso2am-micro-gw-toolkit-3.0.1|' {{ $image.microgateway.projectName }}/{{ $image.microgateway.deploymentConfigPath }}

                micro-gw build {{ $image.microgateway.projectName }} --deployment-config {{ $image.microgateway.projectName }}/conf/deployment-config.toml

                docker login -u \$REGISTRY_USERNAME -p \$REGISTRY_PASSWORD

                REGISTRY_INFO=\$(grep 'registry' {{ $image.microgateway.projectName }}/conf/deployment-config.toml | awk -F"'" '{print \$2}')
                REGISTRY=\$(echo \$REGISTRY_INFO | cut -d "/" -f1)
                ORGANIZATION=\$(echo \$REGISTRY_INFO | cut -d "/" -f2)

                USER_REPO_TAG=\$TAG-`timestamp`
                docker tag \$REGISTRY/\$ORGANIZATION/{{ $image.repository }}:\$TAG {{ $root.Values.registry.address }}/{{ $image.organization }}/{{ $image.repository }}:\$USER_REPO_TAG

                # Push latest tag
                docker tag \$REGISTRY/\$ORGANIZATION/{{ $image.repository }}:\$TAG {{ $root.Values.registry.address }}/{{ $image.organization }}/{{ $image.repository }};
                docker push {{ $root.Values.registry.address }}/{{ $image.organization }}/{{ $image.repository }};

                docker push {{ $root.Values.registry.address }}/{{ $image.organization }}/{{ $image.repository }}:\$USER_REPO_TAG
              """)
            }
          }
      {{- end }}

      {{- end }}
      - script: >
          job("{{ .name }}/push-chart-to-spinnaker") {
            description()
            logRotator(10)
            keepDependencies(false)
            disabled(false)
            concurrentBuild(true)
            scm {
                git {
                    remote {
                        name('chart-repo')
                        url('{{ .chart.repo }}')
                        credentials('github_credentials')
                    }
                }
            }
            triggers {
                scm('* * * * *')
            }
            steps {
              shell(
              """
              cat {{ .chart.name }}/values-dev.yaml | base64 >test
              VALUES_DEV_CONTENT=`tr -d '\\n' < test`

              cat {{ .chart.name }}/values-staging.yaml | base64 >test
              VALUES_STAGING_CONTENT=`tr -d '\\n' < test`

              cat {{ .chart.name }}/values-prod.yaml | base64 >test
              VALUES_PROD_CONTENT=`tr -d '\\n' < test`

              rm {{ .chart.name }}-*.tgz || ls

              {{- if .chart.customChart }}
              helm package {{ .chart.name }} -u
              {{- else }}
              helm repo add wso2 https://helm.wso2.com
              helm repo update
              helm fetch wso2/{{ .chart.name }} --version {{ .chart.version }}
              {{- end }}

              CHART_NAME=`find {{ .chart.name }}-*.tgz`
              cat \$CHART_NAME | base64 > test
              CHART_CONTENT=`tr -d '\\n' < test`

              echo '{"application": "{{ $application.name }}", "artifacts": [ {"type": "embedded/base64","name": "'"\$CHART_NAME"'",
              "reference": "'"\$CHART_CONTENT"'" }, {"type": "embedded/base64","name": "values-dev.yaml","reference": "'"\$VALUES_DEV_CONTENT"'" }, {"type": "embedded/base64","name": "values-prod.yaml","reference": "'"\$VALUES_PROD_CONTENT"'" }, {"type": "embedded/base64","name": "values-staging.yaml","reference": "'"\$VALUES_STAGING_CONTENT"'" } ]}' > data.json

              APP_ENDPOINT=http://spin-gate.{{ $namespace }}.svc.cluster.local:8084/applications/{{ .name }}
              while [ "\$(curl -s -o /dev/null -w ''%{http_code}'' \$APP_ENDPOINT)" != "200" ]; do sleep 60; done
              WEBHOOK_ENDPOINT=http://spin-gate.{{ $namespace }}.svc.cluster.local:8084/webhooks/webhook/chart
              while [ "\$(curl -s -o /dev/null -w ''%{http_code}'' -X POST --header "Content-Type: application/json" --request POST --data @data.json \$WEBHOOK_ENDPOINT)" != "200" ]; do sleep 60; done
              """)
            }
          }
      {{- end }}
