#!/bin/bash
#set -eux
set -o pipefail

# (c) cavaliba.com - DATA Export backup script
#
# crontab example
# 45 */6 * * * /opt/cavaliba/script/data_backup.sh > /tmp/backup_data.log 2>&1


BACKUPDIR="/opt/cavaliba/files/backup"
USER="root"
PASSWORD="xxxxxxxxxxxxxxxxxxx"

cd $BACKUPDIR

DAY=$(date "+%u")
HOUR=$(date "+%H")


DATE=$(date +%Y%m%d_%H:%M:%S)
FILE="$BACKUPDIR/${DAY}_${HOUR}_schema.zst"
echo "$DATE start dumping SCHEMA to $FILE"
docker exec cavaliba_app python manage.py dumpdata --format json --indent 2 app_data.dataschema --natural-primary --natural-foreign | zstd >$FILE

DATE=$(date +%Y%m%d_%H:%M:%S)
FILE="$BACKUPDIR/${DAY}_${HOUR}_classname.zst"
echo "$DATE start dumping CLASS to $FILE"
docker exec cavaliba_app python manage.py dumpdata --format json --indent 2 app_data.dataclass --natural-primary --natural-foreign | zstd >$FILE

DATE=$(date +%Y%m%d_%H:%M:%S)
FILE="$BACKUPDIR/${DAY}_${HOUR}_instance.zst"
echo "$DATE start dumping INSTANCE to $FILE"
docker exec cavaliba_app python manage.py dumpdata --format json --indent 2 app_data.datainstance --natural-primary --natural-foreign | zstd >$FILE

DATE=$(date +%Y%m%d_%H:%M:%S)
FILE="$BACKUPDIR/${DAY}_${HOUR}_conf.zst"
echo "$DATE start dumping CONF to $FILE"
docker exec cavaliba_app python manage.py dumpdata --format json --indent 2 app_home.cavalibaconfiguration --natural-primary --natural-foreign | zstd >$FILE


DATE=$(date +%Y%m%d_%H:%M:%S)
FILE="$BACKUPDIR/${DAY}_${HOUR}_iam.zst"
echo "$DATE start dumping IAM (USER GROUPS PERM ROLES) to $FILE"
docker exec cavaliba_app python manage.py dumpdata --format json --indent 2 app_user --natural-primary --natural-foreign | zstd >$FILE

DATE=$(date +%Y%m%d_%H:%M:%S)
FILE="$BACKUPDIR/${DAY}_${HOUR}_status.zst"
echo "$DATE start dumping STATUS (Raw/Day/Hour) to $FILE"
docker exec cavaliba_app python manage.py dumpdata --format json --indent 2 app_status --natural-primary --natural-foreign | zstd >$FILE



DATE=$(date +%Y%m%d_%H:%M:%S)
echo "$DATE done."
exit 0
