#!/bin/bash

# Specify your backup directory
BACKUP_DIR=/mnt/backups

# List available stacks for backup
echo "Available stacks for recovery:"
STACKS=($(ls $BACKUP_DIR))

select STACK_NAME in "${STACKS[@]}"; do
    # Verify stack backup directory exists
    STACK_BACKUP_DIR=$BACKUP_DIR/$STACK_NAME
    if [ -d $STACK_BACKUP_DIR ]; then
        break
    else
        echo "Invalid selection"
    fi
done

# List available backups for the stack
echo "Available backups for stack $STACK_NAME:"
BACKUPS=($(ls $STACK_BACKUP_DIR/backup_*.txt))

# Display only the timestamps
TIMESTAMPS=("${BACKUPS[@]##*_}")

select CHOICE in "${TIMESTAMPS[@]}"; do
    # Get the full filename of the chosen backup
    BACKUP_FILE=$(echo "${BACKUPS[@]}" | tr ' ' '\n' | grep $CHOICE)
    if [ -f $BACKUP_FILE ]; then
        break
    else
        echo "Invalid selection"
    fi
done

# Extract original Docker Compose file path
COMPOSE_FILE=$(head -n 1 $BACKUP_FILE)
DIR=$(dirname "${COMPOSE_FILE}")

# Check if stack is running and stop it
docker-compose -f $COMPOSE_FILE down

# Rename existing Docker Compose directory
mv $DIR $DIR.recovery_$(date +"%Y%m%d%H%M%S")

# Restore files from backup
tar -xzvf $STACK_BACKUP_DIR/$(sed '2q;d' $BACKUP_FILE) -C /

# Load Docker images from backup
tail -n +3 $BACKUP_FILE | while read IMAGE_FILE; do
    docker load < $STACK_BACKUP_DIR/$IMAGE_FILE
done

# Change to the Docker Compose directory and restart the Docker Compose stack
cd $DIR
docker-compose up -d
