{#
Copyright 2016 Google Inc. 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.
#}

{% macro diskName(diskObj) -%}{{ env["deployment"]}}-{{ diskObj["usage"] }}{%- endmacro %}

{% set NAME_PREFIX = env['deployment'] %}
{% set SQL_INSTANCE_NAME =  env['deployment'] + '-mysql' %}

resources:
{% if properties['createPipelinePersistentStorage'] %}
{% for diskObj in properties["disks"] %}
- name: {{ diskName(diskObj) }}
  type: compute.v1.disk
  properties:
    zone: {{ properties["zone"] }}
    sizeGb: {{ diskObj["sizeGb"] }}
    type: https://www.googleapis.com/compute/v1/projects/{{ env["project"] }}/zones/{{ properties["zone"] }}/diskTypes/{{ diskObj["diskType"] }}
{% endfor %}
{% endif %}

{% if properties['enable_cloudsql'] %}
- name: {{ SQL_INSTANCE_NAME }}
  type: sqladmin.v1beta4.instance
  properties:
    backendType: SECOND_GEN
    instanceType: CLOUD_SQL_INSTANCE
    databaseVersion: {{ properties['cloudsql']['databaseVersion'] }}
    region: {{ properties['cloudsql']['region'] }}
    settings:
      tier: {{ properties['cloudsql']['tier'] }}
      dataDiskSizeGb: {{ properties['cloudsql']['dataDiskSizeGb'] }}
      dataDiskType: {{ properties['cloudsql']['dataDiskType'] }}
      storageAutoResize: true
      replicationType: SYNCHRONOUS
      locationPreference:
        zone: {{ properties['cloudsql']['zone'] }}
      {% if properties['databaseFlags'] %}
      databaseFlags: {{ properties['databaseFlags'] }}
      {% endif %}
      activationPolicy: ALWAYS
      backupConfiguration:
        enabled: true
        binaryLogEnabled: true
        startTime: {{ properties['cloudsql']['backupStartTime'] }}
      ipConfiguration:
        privateNetwork: projects/{{ env['project'] }}/global/networks/default
        authorizedNetworks: {{ properties['cloudsql']['authorizedNetworks'] }}

- name: {{ SQL_INSTANCE_NAME }}-db
  type: sqladmin.v1beta4.database
  properties:
    name: {{ properties['database']['name'] }}
    instance: $(ref.{{ SQL_INSTANCE_NAME }}.name)
    charset: {{ properties['database']['charset'] }}

- name: {{ SQL_INSTANCE_NAME }}-db-root
  type: sqladmin.v1beta4.user
  properties:
    name: {{ properties['dbUser']['name'] }}
    host:  "{{ properties['dbUser']['host'] }}"
    instance: $(ref.{{ SQL_INSTANCE_NAME }}.name)
  metadata:
    dependsOn:
      - {{ SQL_INSTANCE_NAME }}-db
{% endif %}
