#!/usr/bin/env bash

set -e

NOW=$(date +%y%m%d-%H%M%S)
CRON=""
if [ "$1" == "cron" ]; then
    CRON="_${1}"
    TODAY=`date '+%Y_%m_%d'`
    echo "Running cron-$(basename $0) for ${TODAY}..."
fi
instance=$(grep fqdn /opt/labca/data/config.json 2>/dev/null | cut -d ":" -f 2- | tr -d " \"," | cut -d"." -f1)
BASE=${NOW}_${instance}${CRON}
TMPDIR=/tmp/$BASE
mkdir -p $TMPDIR/nginx_ssl
mkdir -p /opt/backup

cd /opt/boulder
docker compose exec bmysql mysqldump boulder_sa_integration >$TMPDIR/boulder_sa_integration.sql

cp -rp /etc/nginx/ssl/* $TMPDIR/nginx_ssl/

cp -rp /opt/labca/data $TMPDIR/
#cp -p /opt/labca/data/config.json $TMPDIR/

cp -rp /opt/boulder/labca/certs/webpki $TMPDIR/

cp -rp /var/lib/softhsm/tokens $TMPDIR/


cd /tmp
tar czf /opt/backup/$BASE.tgz $BASE
rm -rf $TMPDIR

# housekeeping
find /opt/backup -name "*_cron_*.tgz" -mtime +31 -exec rm -rf {} \;

if [ "$1" != "cron" ]; then
    echo /opt/backup/$BASE.tgz
fi
