#!/bin/bash

[ "$MONGO_HOST" ] || {
    echo "You must define \$MONGO_HOST variable." >&2
    exit 1
}


mongo_databases() {
    echo "show dbs" | mongo --quiet --host "$MONGO_HOST"  | cut -f 1 -d " "
}

dbs=$(mongo_databases)

BACKUP_ROOT=/var/backups/mongo
mkdir -p "$BACKUP_ROOT"
for db in $dbs; do
    if [[ "$db" == "local" || "$db" == "config" ]]; then
        continue
    fi
    for exclude_db in $exclude_dbs; do
        if [ "$exclude_db" == "$db" ]; then
            echo "No backup for database $db as it is listed in 'exclude-dbs'."
            continue 2
        fi
    done

    dst="$BACKUP_ROOT/$db"
    [ -d "$dst.old" ] && rm -rf "$dst.old"
    [ -d "$dst" ] && mv "$dst" "$dst.old"
    mkdir -p "$dst.inprogress"
    (( start = SECONDS ))
    echo "Dumping database $db..." >&2
    mongodump --host "$MONGO_HOST" --db "$db" --out "$dst.inprogress" &&
        mv "$dst.inprogress/$db/"* "$dst.inprogress/" &&
        rmdir "$dst.inprogress/$db"
    errlvl="${PIPESTATUS[0]}"
    (( elapsed = SECONDS - start ))
    if [ "$errlvl" != "0" ]; then
        echo "  !! Error when dumping database $db." >&2
        rm -rf "$dst.inprogress" &&
        [ -d "$dst.old" ] && rm -rf "$dst.old"
    else
        mv "$dst.inprogress" "$dst"
        [ -d "$dst.old" ] && rm -rf "$dst.old"
        printf "  ..dumped %-35s (%12s in %10s)\n" "$db" "$(du -sh "$dst" | cut -f 1)" "${elapsed}s" >&2
    fi
done