# _helpers.tpl
{{/* vim: set filetype=mustache: */}}
{{/*
Expand the name of the chart.
*/}}
{{- define "mysqldump.name" -}}
{{- default .Chart.Name .Values.nameOverride | trunc 63 | trimSuffix "-" -}}
{{- end -}}

{{/*
Create a default fully qualified app name.
We truncate at 63 chars because some Kubernetes name fields are limited to this (by the DNS naming spec).
If release name contains chart name it will be used as a full name.
*/}}
{{- define "mysqldump.fullname" -}}
{{- if .Values.fullnameOverride -}}
{{- .Values.fullnameOverride | trunc 63 | trimSuffix "-" -}}
{{- else -}}
{{- $name := default .Chart.Name .Values.nameOverride -}}
{{- if contains $name .Release.Name -}}
{{- .Release.Name | trunc 63 | trimSuffix "-" -}}
{{- else -}}
{{- printf "%s-%s" .Release.Name $name | trunc 63 | trimSuffix "-" -}}
{{- end -}}
{{- end -}}
{{- end -}}

{{/*
Create chart name and version as used by the chart label.
*/}}
{{- define "mysqldump.chart" -}}
{{- printf "%s-%s" .Chart.Name .Chart.Version | replace "+" "_" | trunc 63 | trimSuffix "-" -}}
{{- end -}}

{{/*
Generate gcp service account secret name
*/}}
{{- define "mysqldump.gcpsecretName" -}}
{{ default ( printf "%s-%s" (include "mysqldump.fullname" .) "gcloud-keyfile" ) .Values.upload.googlestoragebucket.existingSecret }}
{{- end -}}

{{/*
Generate gcp service account name
*/}}
{{- define "mysqldump.serviceAccountName" -}}
{{ default (include "mysqldump.fullname" .) .Values.upload.googlestoragebucket.serviceAccountName }}
{{- end -}}

{{/*
Common labels
*/}}
{{- define "mysqldump.labels" -}}
app.kubernetes.io/name: {{ include "mysqldump.name" . }}
helm.sh/chart: {{ include "mysqldump.chart" . }}
app.kubernetes.io/instance: {{ .Release.Name }}
{{- if .Chart.AppVersion }}
app.kubernetes.io/version: {{ .Chart.AppVersion | quote }}
{{- end }}
app.kubernetes.io/managed-by: {{ .Release.Service }}
{{- end -}}
 # configmap.yaml
apiVersion: v1
kind: ConfigMap
metadata:
  name: {{ template "mysqldump.fullname" . }}
  labels:
{{ include "mysqldump.labels" . | indent 4 }}
data:
  MYSQL_HOST: {{ .Values.mysql.host | quote }}
  MYSQL_USERNAME: {{ .Values.mysql.username | quote }}
  MYSQL_PORT: {{ .Values.mysql.port | quote }}
  MYSQL_OPTS: {{ .Values.options | quote }}
  KEEP_DAYS: {{ .Values.housekeeping.keepDays | quote }}
{{- if .Values.upload.openstack.enabled }}
  OS_AUTH_URL: {{ .Values.upload.openstack.authUrl }}
  OS_PROJECT_NAME: {{ .Values.upload.openstack.project }}
  OS_PROJECT_DOMAIN_NAME: {{ .Values.upload.openstack.projectDomain }}
  OS_USERNAME: {{ .Values.upload.openstack.user }}
  OS_USER_DOMAIN_NAME: {{ .Values.upload.openstack.userDomain }}
{{- end }}
---
apiVersion: v1
kind: ConfigMap
metadata:
  name: {{ template "mysqldump.fullname" . }}-script
  labels:
{{ include "mysqldump.labels" . | indent 4 }}
data:
  openstack-upload.py: |-
{{ .Files.Get "files/openstack-upload.py" | indent 4 }}
  backup.sh: |-
    #!/bin/sh
    #
    # mysql backup script
    #
    {{ if .Values.debug }}
    set -ex
    {{ end }}
    BACKUP_DIR="/backup"
    TIMESTAMP="$(date +%Y%m%d%H%M%S)"

    echo "test mysql connection"
    if [ -z "$(mysql -h ${MYSQL_HOST} -P ${MYSQL_PORT} -u ${MYSQL_USERNAME} -B -N -e 'SHOW DATABASES;')" ]; then
      echo "mysql connection failed! exiting..."
      exit 1
    fi

    echo "started" > ${BACKUP_DIR}/${TIMESTAMP}.state

    {{ if or (.Values.persistence.enabled) (.Values.persistentVolumeClaim) }}
    {{ if .Values.housekeeping.enabled }}
    echo "delete old backups"
    find ${BACKUP_DIR} -maxdepth 2 -mtime +${KEEP_DAYS} -regex "^${BACKUP_DIR}/.*[0-9]*_.*\.sql\.gz$" -type f -exec rm {} \;
    {{ end -}}
    {{ end -}}

    {{ if and (.Values.mysql.db) (eq .Values.allDatabases.enabled false) }}
    MYSQL_DB="{{ .Values.mysql.db }}"
    echo "Backing up single db ${MYSQL_DB}"
    {{ if .Values.saveToDirectory }}mkdir -p "${BACKUP_DIR}"/"${MYSQL_DB}"{{ end }}
    mysqldump ${MYSQL_OPTS} -h ${MYSQL_HOST} -P ${MYSQL_PORT} -u ${MYSQL_USERNAME} --databases ${MYSQL_DB} | gzip > ${BACKUP_DIR}/{{ if .Values.saveToDirectory }}${MYSQL_DB}/{{ end }}${TIMESTAMP}_${MYSQL_DB}.sql.gz
    rc=$?
    {{ else if and (.Values.allDatabases.enabled) (eq .Values.allDatabases.singleBackupFile false)}}
    for MYSQL_DB in $(mysql -h "${MYSQL_HOST}" -P ${MYSQL_PORT} -u ${MYSQL_USERNAME} -B -N -e "SHOW DATABASES;"|egrep -v '^(information|performance)_schema$'); do
      echo "Backing up db ${MYSQL_DB}"
      {{ if .Values.saveToDirectory }}mkdir -p "${BACKUP_DIR}"/"${MYSQL_DB}"{{ end }}
      mysqldump ${MYSQL_OPTS} -h ${MYSQL_HOST} -P ${MYSQL_PORT} -u ${MYSQL_USERNAME} --databases ${MYSQL_DB} | gzip > ${BACKUP_DIR}/{{ if .Values.saveToDirectory }}${MYSQL_DB}/{{ end }}${TIMESTAMP}_${MYSQL_DB}.sql.gz
      rc=$?
    done

    {{ else if and (.Values.allDatabases.enabled) (.Values.allDatabases.singleBackupFile) }}
    echo "Backing up all databases"
    MYSQL_DB="alldatabases"
    {{ if .Values.saveToDirectory }}mkdir -p "${BACKUP_DIR}"/"${MYSQL_DB}"{{ end }}
    mysqldump ${MYSQL_OPTS} -h ${MYSQL_HOST} -P ${MYSQL_PORT} -u ${MYSQL_USERNAME} --all-databases | gzip > ${BACKUP_DIR}/{{ if .Values.saveToDirectory }}${MYSQL_DB}/{{ end }}${TIMESTAMP}_${MYSQL_DB}.sql.gz
    rc=$?
    {{- end -}}

    {{- if or (.Values.upload.googlestoragebucket.enabled) (.Values.upload.ssh.enabled) (.Values.upload.openstack.enabled) -}}
    {{ if .Values.upload.ssh.enabled -}}
    echo "upload files via ssh to {{ .Values.upload.ssh.user }}@{{ .Values.upload.ssh.host }}:{{ .Values.upload.ssh.dir }}"
    rsync -av --delete --exclude=*.state -e 'ssh -o StrictHostKeyChecking=accept-new -o UserKnownHostsFile=/dev/null' ${BACKUP_DIR}/ {{ .Values.upload.ssh.user }}@{{ .Values.upload.ssh.host }}:{{ .Values.upload.ssh.dir }}
    rcu=$?
    {{ end -}}

    {{ if .Values.upload.googlestoragebucket.enabled -}}
    echo "upload files to google storage bucket {{ .Values.upload.googlestoragebucket.bucketname }}"
    gcloud auth activate-service-account --key-file /root/gcloud/{{ .Values.upload.googlestoragebucket.secretFileName }}
    gsutil -m rsync -r -x '.*\.state' -d ${BACKUP_DIR}/ {{ .Values.upload.googlestoragebucket.bucketname }}
    rcu=$?
    {{ end }}

    {{ if .Values.upload.openstack.enabled -}}
    echo "upload files to openstack at {{ .Values.upload.openstack.destination }}"
    python /scripts/openstack-upload.py \
      --source=${BACKUP_DIR} \
      --destination={{ .Values.upload.openstack.destination }} \
      {{ if .Values.upload.openstack.ttlDays -}} --ttl-days={{ .Values.upload.openstack.ttlDays }} {{- end }} \
      {{ if .Values.debug -}} --verbose {{- end }}
    rcu=$?
    {{ end }}

    if [ "$rcu" != "0" ]; then
      echo "upload failed"
      exit 1
    fi

    {{- else  }}
    {{ if .Values.dumpAllToStdout }}
    mysqldump ${MYSQL_OPTS} -h ${MYSQL_HOST} -P ${MYSQL_PORT} -u ${MYSQL_USERNAME} --all-databases
    rc=$?
    {{ end }}
    {{ end }}

    {{ if .Values.debug }}
      echo Contents of ${BACKUP_DIR}
      ls -lahR ${BACKUP_DIR}
    {{ end }}

    if [ "$rc" != "0" ]; then
      echo "backup failed"
      exit 1
    fi

    {{ if .Values.additionalSteps }}
     {{- range .Values.additionalSteps }}
      {{ . }}
     {{- end }}
    {{- end }}

    echo "complete" > ${BACKUP_DIR}/${TIMESTAMP}.state

    echo "Disk usage in ${BACKUP_DIR}"
    du -h -d 2 ${BACKUP_DIR}

    echo "Backup successful! :-)"
 # cron.yaml
{{- if ne .Values.schedule "now" -}}
apiVersion: batch/v1beta1
kind: CronJob
metadata:
  name: {{ template "mysqldump.fullname" . }}
  labels:
{{ include "mysqldump.labels" . | indent 4 }}
spec:
  schedule: "{{ .Values.schedule }}"
  successfulJobsHistoryLimit: {{ .Values.successfulJobsHistoryLimit }}
  failedJobsHistoryLimit: {{ .Values.failedJobsHistoryLimit }}
  concurrencyPolicy: Forbid
  jobTemplate:
    metadata:
      labels:
        app: {{ template "mysqldump.name" . }}
        chart: {{ template "mysqldump.chart" . }}
        cronjob-name: {{ template "mysqldump.fullname" . }}
        release: "{{ .Release.Name }}"
        heritage: "{{ .Release.Service }}"
    spec:
      backoffLimit: 1
      template:
{{- $file := .Files.Get "files/job.tpl" }}
{{ tpl $file . | indent 8 }}
{{ end }}
 # gcpserviceaccount.yaml
{{- if .Values.upload.googlestoragebucket.usingGCPController }}
apiVersion: gcp.kiwigrid.com/v1beta1
kind: GcpServiceAccount
metadata:
  labels:
    controller-tools.k8s.io: "1.0"
{{ include "mysqldump.labels" . | indent 4 }}
  name: {{ template "mysqldump.fullname" . }}
spec:
  serviceAccountIdentifier: {{ template "mysqldump.serviceAccountName" . }}
  serviceAccountDescription: Service account for accessing a storage bucket for mysql backups
  secretName: {{ template "mysqldump.gcpsecretName" . }}
  bindings:
  - resource: buckets/{{ index (splitList "/" (.Values.upload.googlestoragebucket.bucketname | replace "gs://" "")) 0  }}
    roles:
    - roles/storage.objectAdmin
{{ end }} # job.yaml
{{- if eq .Values.schedule "now" -}}
apiVersion: batch/v1
kind: Job
metadata:
  name: {{ template "mysqldump.fullname" . }}
  labels:
{{ include "mysqldump.labels" . | indent 4 }}
spec:
  backoffLimit: 1
  template:
{{- $file := .Files.Get "files/job.tpl" }}
{{ tpl $file . | indent 4 }}
{{ end }}
 # pvc.yaml
{{- if .Values.persistence.enabled }}
{{- if not .Values.persistentVolumeClaim }}
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  name: {{ template "mysqldump.fullname" . }}
  labels:
{{ include "mysqldump.labels" . | indent 4 }}
spec:
  accessModes: [{{ .Values.persistence.accessMode | quote }}]
  {{- if .Values.persistence.storageClass }}
  {{- if (eq "-" .Values.persistence.storageClass) }}
  storageClassName: ""
  {{- else }}
  storageClassName: "{{ .Values.persistence.storageClass }}"
  {{- end }}
  {{- end }}
  resources:
    requests:
      storage: {{ .Values.persistence.size }}
{{- end -}}
{{- end -}}
 # secret.yaml
{{- if .Values.mysql.password }}
apiVersion: v1
kind: Secret
metadata:
  name: "{{ template "mysqldump.fullname" . }}"
  labels:
{{ include "mysqldump.labels" . | indent 4 }}
type: Opaque
data:
  MYSQL_PWD: {{ .Values.mysql.password | b64enc | quote }}
{{- if and (.Values.upload.openstack.enabled) (not .Values.upload.openstack.existingSecret) }}
  OS_PASSWORD: {{ .Values.upload.openstack.password | b64enc | quote }}
{{- end }}
---
{{- end }}
{{- if .Values.upload.ssh.enabled }}
apiVersion: v1
kind: Secret
metadata:
  name: "{{ template "mysqldump.fullname" . }}-ssh-privatekey"
  labels:
{{ include "mysqldump.labels" . | indent 4 }}
type: Opaque
stringData:
  id_rsa: {{ .Values.upload.ssh.privatekey | quote }}
---
{{- end }}
{{- if .Values.upload.googlestoragebucket.enabled }}
{{- if not .Values.upload.googlestoragebucket.existingSecret }}
{{- if not .Values.upload.googlestoragebucket.usingGCPController }}
apiVersion: v1
kind: Secret
metadata:
  name: {{ template "mysqldump.gcpsecretName" . }}
  labels:
{{ include "mysqldump.labels" . | indent 4 }}
type: Opaque
stringData:
  {{ .Values.upload.googlestoragebucket.secretFileName }}: {{ .Values.upload.googlestoragebucket.jsonKeyfile | quote }}
{{ end }}
{{ end }}
{{ end }}
# Default values for mysqldump.
# This is a YAML-formatted file.
# Declare variables to be passed into your templates.

image:
  registry: docker.io
  repository: monotek/gcloud-mysql
  tag: "8"
  ## Specify a imagePullPolicy
  ## Defaults to 'Always' if image tag is 'latest', else set to 'IfNotPresent'
  ## ref: http://kubernetes.io/docs/user-guide/images/#pre-pulling-images#
  pullPolicy: IfNotPresent

mysql:
## Without a host set, this chart will not do anything as it is expected
## to be used only when there's an existing database to backup.
  host: ""
  username: root
  # overriden by existingDbSecret / existingDbSecretKey if set
  password:
  port: 3306
  # db for single db backup
  db: dbname
  # Get password from existing secret
  # existingSecret:
  # existingSecretKey:

# use --all-databases if enabled
allDatabases:
  enabled: true
  # creates single backup file with all databases
  singleBackupFile: false

# options to pass to mysqldump
options: "--opt --single-transaction"

# save sql backup to a directory named like the database or "alldatabases"
saveToDirectory: false

# if to dump all databases to stdout when not uploading
dumpAllToStdout: false

## set to `now` to get a one time job, or a cronjob schedule like `0 0 * * *`
## to get a cronjob.
schedule: "0 3 * * *"

# enable some debug options
debug: false

# cronjob history
successfulJobsHistoryLimit: 5
failedJobsHistoryLimit: 5

# additional steps for mysqldump shell script
# will be inserted after all backup and upload jobs completed successfully.
# Use "${BACKUP_DIR}/${TIMESTAMP}_${MYSQL_DB}.sql.gz" as dump file name.
# see examples
additionalSteps: []
#  - gsutil cp "${BACKUP_DIR}/${TIMESTAMP}_${MYSQL_DB}.sql.gz" gs://mybucket/latest.sql.gz
#  - echo "latest sql dump updated"

## set persistentVolumeClaim to use a PVC that already exists.
## if set will override any settings under `persistence` otherwise
## if not set and `persistence.enabled` set to true, will create a PVC.
# persistentVolumeClaim: <existing-PVC>

persistence:
  enabled: true
  size: 8Gi
  accessMode: ReadWriteOnce
  subPath:
  ## If defined, storageClassName: <storageClass>
  ## If set to "-", storageClassName: "", which disables dynamic provisioning
  ## If undefined (the default) or set to null, no storageClassName spec is
  ##   set, choosing the default provisioner.  (gp2 on AWS, standard on
  ##   GKE, AWS & OpenStack)
  ##
  # storageClass: "-"

# delete old backups
housekeeping:
  enabled: true
  keepDays: 10

# upload backup
upload:
  googlestoragebucket:
    enabled: false
    # bucketname with gs:// prefix
    bucketname: gs://mybucket/test
    # jsonKeyfile of you serviceaccount as string
    jsonKeyfile: ""
    # secretFileName specifies the keyfile name inside the secret
    secretFileName: keyfile.json
    # existingSecret can be enabled to use an existing secret
    # existingSecret: mysecret
    # serviceAccountName to set a specific service account name
    # serviceAccountName
    # usingGCPController to enable autogeneration and injection of the service account
    usingGCPController: false

  ssh:
    enabled: false
    user: backup
    host: yourdomain.com
    dir: /backup
    # id_rsa private key as string
    privatekey: ""

  openstack:
    enabled: false
    user: backup@mydomain
    userDomain: default
    # overriden by used if secretName/secretKey set
    password:
    authUrl: https://mydomain:5000/v3
    project: my_project
    projectDomain: default
    # container/folder(/subfolder ...)
    destination: backup/mysql
    # existingSecret can be enabled to use an existing secret
    # existingSecret:
    # existingSecretKey defines the key to use, or 'openstack-backup-password' if not set
    # existingSecretKey:
    # set to 0 to disable TTL on uploaded files
    ttlDays: 30

resources: {}
  # We usually recommend not to specify default resources and to leave this as a conscious
  # choice for the user. This also increases chances charts run on environments with little
  # resources, such as Minikube. If you do want to specify resources, uncomment the following
  # lines, adjust them as necessary, and remove the curly braces after 'resources:'.
  # limits:
  #  cpu: 100m
  #  memory: 128Mi
  # requests:
  #  cpu: 100m
  #  memory: 128Mi

nodeSelector: {}

tolerations: []

affinity: {}

## Pod Security Context
securityContext:
  enabled: false
  fsGroup: 999
  runAsUser: 999
