#!/bin/bash

# Check if the Docker Compose file was provided
if [ $# -eq 0 ]; then
    echo "No Docker Compose file provided"
    exit 1
fi

COMPOSE_FILE=$1
DIR=$(dirname "${COMPOSE_FILE}")
BASE_DIR_NAME=$(basename "${DIR}")
BACKUP_DIR=/mnt/backups/$BASE_DIR_NAME
TIMESTAMP=$(date +"%Y%m%d%H%M%S")

# Create a new backup directory for this stack if it doesn't already exist
mkdir -p $BACKUP_DIR

# Stop the Docker Compose stack
docker-compose -f $COMPOSE_FILE down

# Tarball the Docker Compose directory
CONFIG_BACKUP_FILE="files_${DIR##*/}"_$TIMESTAMP.tar.gz
tar -czvf $BACKUP_DIR/$CONFIG_BACKUP_FILE -C / $DIR

# Identify and save each Docker image used by the stack
IMAGES=$(docker-compose -f $COMPOSE_FILE config | awk '{if ($1 == "image:") print $2;}')
BACKUP_FILE=$BACKUP_DIR/"backup_${BASE_DIR_NAME}_${TIMESTAMP}.txt"

# Clear the backup list file
echo  "${COMPOSE_FILE}" > $BACKUP_FILE

# Write config backup file name to the backup list file
echo $CONFIG_BACKUP_FILE >> $BACKUP_FILE

for IMAGE in $IMAGES; do
    # Get image id (strip off "sha256:" prefix)
    IMAGE_ID=$(docker inspect --format="{{.Id}}" $IMAGE | sed 's/sha256://')

    # Check if the image backup file already exists
    IMAGE_BACKUP_FILE="image_${IMAGE//[:\/]/_}_${IMAGE_ID}.tar.gz"
    IMAGE_BACKUP=$BACKUP_DIR/$IMAGE_BACKUP_FILE
    if [ ! -f $IMAGE_BACKUP ]; then
        docker save $IMAGE | gzip > $IMAGE_BACKUP
    fi

    # Write image backup file name to the backup list file
    echo $IMAGE_BACKUP_FILE >> $BACKUP_FILE
done

# Restart the Docker Compose stack
docker-compose -f $COMPOSE_FILE up -d
