apiVersion: v1
kind: ConfigMap
metadata:
  name: {{ template "mysqldump.fullname" . }}-script
  labels:
    app: {{ template "mysqldump.name" . }}
    chart: {{ template "mysqldump.chart" . }}
    release: "{{ .Release.Name }}"
    heritage: "{{ .Release.Service }}"
data:
  backup.sh: |-
{{- if .Values.debug }}
    set -x
{{- end }}
    if [[ -z ${MYSQL_HOST} ]]; then
      echo "no MySQL host specified.  Nothing to do here."
      exit 0
    fi
    echo "Backing up database"
    DATE=$(date +%Y%m%d%H%M%S)
    echo "started" > /backup/${DATE}.state
    [[ -n ${MYSQL_USERNAME} ]] && USER="--user=${MYSQL_USERNAME}"
    [[ -n ${MYSQL_PASSWORD} ]] && PASS="--password=${MYSQL_PASSWORD}"
    [[ -n ${MYSQL_HOST} ]] && HOST="--host=${MYSQL_HOST}"
    [[ -n ${MYSQL_PORT} ]] && PORT="--port=${MYSQL_PORT}"
    CREDS="${USER} ${PASS} ${HOST} ${PORT}"
{{- if (.Values.persistence.enabled) or (.Values.persistentVolumeClaim) }}
    mysqldump ${CREDS} ${MYSQL_OPTS} > /backup/${DATE}.sql
{{- else }}
    mysqldump ${CREDS} ${MYSQL_OPTS}
{{- end }}
    rc=$?
    if [[ $rc != 0 ]]; then
      echo "backup failed"
      exit 1
    fi
    echo "complete" > /backup/${DATE}.state
    echo "backup complete - /backup/${DATE}.sql"
{{- if .Values.debug }}
    ls -alh /backup
{{- end -}}
