apiVersion: v1
kind: ConfigMap
metadata:
  name: vault-backup-script
  namespace: vault
  labels:
    app.kubernetes.io/name: vault-backup-script
    app.kubernetes.io/instance: vault
    app.kubernetes.io/part-of: vault
data:
  backup.sh: |
    echo " ";
    echo ">> Running S3 backup for Vault snapshot";
    OUTPUT=$(s3cmd sync --no-check-certificate -v /opt/backup/* "${BUCKET}/cl01tl/cl01tl-vault-snapshots/" 2>&1)
    STATUS=$?

    if [ $STATUS -ne 0 ]; then
        if echo "$OUTPUT" | grep -q "403 Forbidden"; then
            MESSAGE="403 Authentication Error: Your keys are wrong or you don't have permission"
        elif echo "$OUTPUT" | grep -q "404 Not Found"; then
            MESSAGE="404 Error: The bucket or folder does not exist"
        elif echo "$OUTPUT" | grep -q "Connection refused"; then
            MESSAGE="Network Error: Cannot reach the S3 endpoint"
        else
            MESSAGE="Unknown Error"
            echo " ";
            echo ">> Unknown Error, output:"
            echo " "
            echo "$OUTPUT"
        fi

        MAX_RETRIES=5
        SUCCESS=false

        echo " "
        echo ">> Sending message to ntfy using curl ..."

        echo " "
        echo ">> Verifying required commands ..."

        for i in $(seq 1 "$MAX_RETRIES"); do
            if apk update 2>&1 >/dev/null; then
                echo ">> Attempt $i: Repositories are reachable";
                SUCCESS=true;
                break;
            else
                echo ">> Attempt $i: Connection failed, retrying in 5 seconds ...";
                sleep 5;
            fi;
        done;

        if [ "$SUCCESS" = false ]; then
            echo ">> ERROR: Could not connect to apk repositories after $MAX_RETRIES attempts, exiting ...";
            exit 1;
        fi

        if ! command -v curl 2>&1 >/dev/null; then
            echo ">> Command curl could not be found, installing";
            apk add --no-cache -q curl;
            if [ $? -eq 0 ]; then
                echo ">> Installation successful";
            else
                echo ">> Installation failed with exit code $?";
                exit 1;
            fi;
        fi;

        echo " "
        echo ">> Sending to NTFY ..."
        echo ">> Message: $MESSAGE"
        HTTP_STATUS=$(curl \
            --silent \
            --write-out '%{http_code}' \
            -H "Authorization: Bearer ${NTFY_TOKEN}" \
            -H "X-Priority: 5" \
            -H "X-Tags: warning" \
            -H "X-Title: Vault Backup Failed for ${TARGET}" \
            -d "$MESSAGE" \
            ${NTFY_ENDPOINT}/${NTFY_TOPIC}
        )
        echo ">> HTTP Status Code: $HTTP_STATUS"

    else
        echo " ";
        echo ">> S3 Sync succeeded"
    fi
