#!/bin/bash
#
# Copyright 2018 Google LLC
#
# 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.

set -euo pipefail

export SCRIPT_DIR=$(readlink -f "$(dirname "${BASH_SOURCE[0]}")")

if [[ ! -f "${SCRIPT_DIR}/util.sh" ]]; then
  >&2 echo "Missing util.sh file, exiting"
  exit 1
fi

USAGE='
This script restores Cassandra cluster data from backup files. Following files
are required:
- multiple backup .tar.gz archives, containing raw data, these files are
  generated by backup.sh script
- backup-schema.cql schema file

Parameters:
--keyspace             (Required) Name of Cassandra keyspace to backup
--namespace            (Required) Name of K8s namespace, where Cassandra
                       cluster exists
--app_instance_name    (Required) Name of application in K8s cluster

Example:
<SCRIPT DIR>/restores.sh   --keyspace demo \
                           --namespace custom-namespace \
                           --app_instance_name cassandra-1
'

. "${SCRIPT_DIR}/util.sh"

add_flag_with_argument KEYSPACE keyspace

init_util $@

required_variables KEYSPACE

current_status

wait_for_healthy_sts

info "Checking if required files exists"
if [[ ! -f backup-schema.cql ]]; then
  info "Missing backup-schema.cql"
  exit 1
fi
info "All required files are available"
info ""
info "Detecting number or archives..."
declare -i backup=0
while [[ -f "backup-${backup}.tar.gz" ]]; do
  info "Found backup-${backup}.tar.gz"
  ((backup+=1))
done
if [[ $backup -eq 0 ]]; then
  info "Cannot find archive file backup-0.tar.gz!"
  exit 1
fi
BACKUPS=$(( backup - 1 ))
REPLICAS=$(get_desired_number_of_replicas_in_sts)
info "Preparing to restore a backup of keyspace '${KEYSPACE}' from ${BACKUPS} archieves"
info "Performing restore of ${REPLICAS} sized cluster"

info "Restoring schema"
kubectl exec -i "${APP_INSTANCE_NAME}-cassandra-0" -n "${NAMESPACE}" -c cassandra -- \
  cqlsh < backup-schema.cql

info "Creating restore instance"
info ""
kubectl apply -f "${SCRIPT_DIR}/controller.yaml" -n "${NAMESPACE}"
info "Wait for the cassandra-restore container"
kubectl wait --for=condition=Ready -n "${NAMESPACE}" --timeout=60s pod cassandra-restore
info "Uploading restore script"
info ""
kubectl cp "${SCRIPT_DIR}/instance_restore.sh" cassandra-restore:/tmp/instance_restore.sh -n "${NAMESPACE}"
SEEDS=$(kubectl get sts -n "${NAMESPACE}" "${STS_NAME}" \
          -ojsonpath='{.spec.template.spec..containers[0].env[?(@.name=="CASSANDRA_SEEDS")].value}' \
          | tr -d [:space:])
for backup in $(seq 0 $(( "${BACKUPS}" - 1 )) ); do
  info "Uploading backup ${backup}"
  info ""
  kubectl cp "backup-${backup}.tar.gz" cassandra-restore:/tmp/backup.tar.gz --namespace "${NAMESPACE}"
  info "Restoring backup..."
  info ""
  kubectl exec -it cassandra-restore --namespace "${NAMESPACE}" -- /tmp/instance_restore.sh "${KEYSPACE}" "${SEEDS}"
done
info "Removing restore instance..."
info ""
kubectl delete -f "${SCRIPT_DIR}/controller.yaml" --namespace "${NAMESPACE}"
info ""

info "Done!"
