#!/bin/bash

# BACKUP SCRIPT
# The backup script is OPTIONAL.
# It is used to backup the service on the server.
# It is called with:
#  1) the path to the server specific env file as the frist argument.
#  2) the path to the destination backup file as the second argument.
# If the backup file already exists, the script should exit with a message.

source "$(dirname "$0")/_common.sh"
load_env "$1" || die "Failed to load environment variables"

# Required environment variables
check_required_env_vars "CONTAINER_NAME" "LOCAL_DATA_FOLDER"

# Get backup file path from second argument
BACKUP_FILE="$2"
if [ -z "$BACKUP_FILE" ]; then
    die "Backup file path not provided"
fi

# Check if backup file already exists
if [ -f "$BACKUP_FILE" ]; then
    die "Backup file $BACKUP_FILE already exists"
fi

# Stop container before backup
_stop_container "$CONTAINER_NAME"

Create backup of data folder
echo "Creating backup of $LOCAL_DATA_FOLDER..."
if ! tar zcvf "$BACKUP_FILE" -C "$LOCAL_DATA_FOLDER" .; then
    _start_container "$CONTAINER_NAME"
    die "Failed to create backup"
fi

# Start container after backup
_start_container "$CONTAINER_NAME"

echo "Backup created successfully: $BACKUP_FILE"