#!/usr/bin/env dash
set -e

{{- if or (eq (printf "%v" .Values.restore.sslVerify) "true") (eq (printf "%v" .Values.restore.sslVerify) "True") }}
{{- if .Values.global.customCACerts }}
# copy system certs to a temp file
# then concat our custom certs to that file
cp -pur {{ include "cmem.cmemc-ca-bundle-path" . }} /custom-cacert/customcacerts.pem
echo "Copied python system CAs from {{ include "cmem.cmemc-ca-bundle-path" . }}"
cat /custom-cacert/cm/* >> /custom-cacert/customcacerts.pem
echo "Concat custom CA to new system CA"
echo "Now using this REQUESTS_CA_BUNDLE: ${REQUESTS_CA_BUNDLE}"
{{- end }}
{{- end }}

echo "=== CMEM Restore Script ==="
echo "Starting restore at $(date)"

# Set restore directory
RESTORE_DIR="{{ .Values.restore.persistence.mountPath }}"
echo "Restore directory: ${RESTORE_DIR}"

# Verify restore directory exists and is writable
if [ ! -d "${RESTORE_DIR}" ]; then
    echo "ERROR: Backup directory ${RESTORE_DIR} does not exist"
    exit 1
fi

if [ ! -w "${RESTORE_DIR}" ]; then
    echo "ERROR: Backup directory ${RESTORE_DIR} is not writable"
    exit 1
fi

# Check available space
AVAILABLE_SPACE=$(df -BG "${RESTORE_DIR}" | tail -1 | awk '{print $4}' | sed 's/G//')
echo "Available space in restore directory: ${AVAILABLE_SPACE}G"

# print the config for debugging
# echo "Verifying cmemc configuration..."
# cmemc config eval

# ensure CMEM is up and responding
echo "Waiting for CMEM to be available..."
RETRY_COUNT=0
MAX_RETRIES=30
while ! cmemc graph list > /dev/null 2>&1; do
    RETRY_COUNT=$((RETRY_COUNT + 1))
    if [ $RETRY_COUNT -ge $MAX_RETRIES ]; then
        echo "ERROR: CMEM did not become available after $MAX_RETRIES attempts"
        exit 1
    fi
    echo "Waiting for CMEM to be available... (attempt $RETRY_COUNT/$MAX_RETRIES)"
    sleep 10
done
echo "CMEM is available!"

# ensure CMEM admin status is healthy
echo "Checking CMEM admin status..."
RETRY_COUNT=0
while ! cmemc admin status --exit-1 error > /dev/null 2>&1; do
    RETRY_COUNT=$((RETRY_COUNT + 1))
    if [ $RETRY_COUNT -ge $MAX_RETRIES ]; then
        echo "ERROR: CMEM admin status check failed after $MAX_RETRIES attempts"
        exit 1
    fi
    echo "Waiting for CMEM admin status to be healthy... (attempt $RETRY_COUNT/$MAX_RETRIES)"
    sleep 10
done
echo "CMEM admin status is healthy!"

# Copy workspace zip file from restore path bucket
aws s3 cp s3://${S3BUCKET}/restore/workspace-backup.zip ${BACKUP_DIR}/${BACKUP_FILE_TAG}${BACKUP_TIMESTAMP}/workspace-backup.zip

# Export store
echo "Trigger graphdb store backup..."
# Variables are fetched from explore configMap
#STORE_GRAPHDB_HOST={{ .Values.explore.store.graphdb.host | quote }}
#STORE_GRAPHDB_PORT={{ .Values.explore.store.graphdb.port | quote }}
#STORE_GRAPHDB_REPOSITORY={{ .Values.explore.store.graphdb.repository | quote }}

export PARAMS_JSON="{\"repositories\":[\"cmem\"], \"removeStaleRepositories\":false\", \"restoreSystemData\":true, \"bucketUri\":\"s3:///${S3BUCKET}/restore/graphdb-cloud-backup.tar?region=${S3REGION}\"}"

curl -X POST --header 'Content-Type: multipart/form-data' --header 'Accept: application/json' \
    --header "Authorization: Basic $(echo -n ${STORE_GRAPHDB_USERNAME}:${STORE_GRAPHDB_PASSWORD} | base64)" \
    -F "params=${PARAMS_JSON}" \
    'http://graphdb:7200/rest/recovery/cloud-restore'

# Restore workspace
echo "Importing workspace..."
cmemc admin workspace import ${BACKUP_DIR}/workspace-backup.zip
echo "Workspace imported to ${BACKUP_DIR}/workspace-backup.zip"

# Reload access conditions of Explore
# This is needed because we could have change the ACL Graph, but did not notify Explore yet by only using the
# cloud-restore from GraphDB.
echo "Reload access conditions of Explore"
echo "Get ACL Graph Export ..."
cmemc graph export https://ns.eccenca.com/data/ac/ --mime-type application/n-triples > ${BACKUP_DIR}/conditions.nt
echo "Import ACL Graph again ..."
cmemc graph import --replace ${BACKUP_DIR}/conditions.nt https://ns.eccenca.com/data/ac/

# Migrate/Bootstrap the instance
# In case we restore in an other version we have to make sure
echo "[$(date +%Y-%m-%d-%H%M%S-%Z)] 4) Migrate resp. bootstrap the instance"
cmemc admin migration execute --all

echo "Restore completed successfully at $(date)"
echo "=== End of Backup Script ==="
