#!/usr/bin/env bash

set -e

FILE=/opt/backup/$1

[ "$1" != "" ] || (echo "You must provide a backup file name to restore"; exit 1)
[ -f $FILE ] || (echo "Backup file '$FILE' not found"; exit 1)

BASE=$(echo "$FILE" | perl -p0e "s/.*\/(.*).tgz/\1/")
TMPDIR=/tmp/$BASE

cd /tmp
tar xzf $FILE 2>&1

cd /opt/boulder
[ -f $TMPDIR/boulder_sa_integration.sql ] || (echo "MySQL backup file not found"; exit 1)
docker compose exec bmysql mysql boulder_sa_integration <$TMPDIR/boulder_sa_integration.sql

if [ -d  $TMPDIR/nginx_ssl ]; then
    if [ -d /etc/nginx/ssl ]; then
        if [ $(ls -1 /etc/nginx/ssl/ | wc -l) -gt 0 ]; then
            rm -rf /etc/nginx/ssl_BAK
            mkdir /etc/nginx/ssl_BAK
            mv /etc/nginx/ssl/* /etc/nginx/ssl_BAK/
        fi
    fi
    if [ -d $TMPDIR/nginx_ssl/ssl ]; then
        mv -f $TMPDIR/nginx_ssl/ssl/* /etc/nginx/ssl/
    else
        mv -f $TMPDIR/nginx_ssl/* /etc/nginx/ssl/
    fi
else
    mv -f $TMPDIR/*key* $TMPDIR/*cert.pem $TMPDIR/*.csr /etc/nginx/ssl/
fi

[ -d  $TMPDIR/data ] || (echo "Data folder backup not found"; exit 1)
vrs=$(grep version /opt/labca/data/config.json | sed -e 's/.*:[ ]*//' | sed -e 's/\",//g' | sed -e 's/\"//g')
rm -rf /opt/labca/data/* && mv $TMPDIR/data/* /opt/labca/data/
sed -i -e "s/\"version\": \".*\"/\"version\": \"$vrs\"/" /opt/labca/data/config.json

if [ -d  $TMPDIR/webpki ]; then
    rm -rf /opt/boulder/labca/certs/webpki/* && mv $TMPDIR/webpki/* /opt/boulder/labca/certs/webpki/
else
    echo "WARNING: public CA files not found in backup"
fi

if [ -d  $TMPDIR/tokens ]; then
    rm -rf /var/lib/softhsm/tokens/* && mv $TMPDIR/tokens/* /var/lib/softhsm/tokens/
else
    echo "WARNING: SoftHSMv2 tokens folder not found in backup"
fi

rm -rf $TMPDIR
