#!/bin/bash
# Copyright 2021 Canonical Ltd.
#
# 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.
#
# For those usages not covered by the Apache License, Version 2.0 please
# contact: legal@canonical.com
#
# To get in touch with the maintainers, please contact:
# osm-charmers@lists.launchpad.net
##

MASTER=`mongo --quiet --eval "d=db.isMaster(); print( d['ismaster'] );"`

TARGET=`action-get target` 
DB_BACKUP_PATH=`action-get path`

mkdir -p $DB_BACKUP_PATH

if [ "$TARGET" == "SECONDARY" ]; then
    if [ "$MASTER" == "true" ]; then
        action-fail "This action should be run in a Secondary"
        exit
    fi
elif [ "$TARGET" == "PRIMARY" ]; then
    if [ "$MASTER" == "false" ]; then
        action-fail "This action should be run in a Primary"
        exit
    fi
fi

mongodump --gzip --archive=$DB_BACKUP_PATH/backup.archive
action-set copy.cmd="kubectl cp $JUJU_MODEL_NAME/$HOSTNAME:$DB_BACKUP_PATH/backup.archive backup.archive"
action-set restore.cmd="kubectl cp backup.archive $JUJU_MODEL_NAME/$HOSTNAME:$DB_BACKUP_PATH/backup.archive"
action-set restore.juju="juju run-action $JUJU_UNIT_NAME restore --wait"

