---
apiVersion: v1
kind: ConfigMap
metadata:
  namespace: meertime
  name: mysql-control-map
  labels:
    app.kubernetes.io/name: mysql-control
data:
  control-mysql.sh: |-
    #!/bin/sh

    set -o errexit
    set -o nounset

    CONTROL_DIR=/mnt/mysql/
    STATE_FILE=${CONTROL_DIR}/mysql-state.cfg
    DESIRED_STATE=wipe_and_init_v0.6_inc_proposals_16.08.20.sql.gz
    DESIRED_STATE_UNPACKED=$(echo $DESIRED_STATE | sed 's/.gz//g')
    CHECKSUM=03ff7db2fa1c730eddce983f6d5fa0c2

    trap "rm -f ${CONTROL_DIR}/${DESIRED_STATE} ${CONTROL_DIR}/${DESIRED_STATE_UNPACKED}" EXIT

    PERFORM_INIT=1

    echo "testing if state file exist"
    if [ -e ${STATE_FILE} ]
    then
      echo "State file exists"
      echo "Verifying contents"
      contents=$(cat ${STATE_FILE})
      echo "Contents of the file are :$contents"
      if [ "${contents}"x != ${DESIRED_STATE}x ] || [ "FORCE_RELOAD"x = "$FORCE_RELOAD"x ]
      then
        PERFORM_INIT=0
      else
        echo "mysql is in desired state"
      fi
    else
      PERFORM_INIT=0
    fi

    if [ "${PERFORM_INIT}" -eq "0" ]
    then
      cd ${CONTROL_DIR}
      /bin/sh /vault/secrets/retrieve-control.sh ${DESIRED_STATE}
      echo "Listing download"
      ls -l ${CONTROL_DIR}/${DESIRED_STATE}
      md5sum_check=$(md5sum ${CONTROL_DIR}/${DESIRED_STATE} | awk '{print $1}')
      if [[ "${md5sum_check}" = "${CHECKSUM}" ]]
      then
        echo "Checksum matches, proceeding"
        gunzip  < ${CONTROL_DIR}/${DESIRED_STATE} | mysql -u $MYSQL_USER -p$MYSQL_PASSWORD -h $DB_HOST $MYSQL_DATABASE
        echo ${DESIRED_STATE} > ${STATE_FILE}
      else
        echo "Checksum of desired state file does not match expectation, aborting"
        echo "Expected ${CHECKSUM} got ${md5sum_check}"
        ls ${CONTROL_DIR}/${DESIRED_STATE}
        exit 1
      fi
    fi

    exit 0
