#!/bin/bash
# v01

# List and check LXC containers
echo "Listing all LXC containers..."
CONTAINERS=($(lxc-ls -1))

# Check if there are any containers
if [[ ${#CONTAINERS[@]} -eq 0 ]]; then
    echo "There are no LXC containers."
    exit 1
fi

echo "Found ${#CONTAINERS[@]} container(s): ${CONTAINERS[@]}"
echo "----------------------------------"

# Loop over each container
for LXCHOSTNAME in "${CONTAINERS[@]}"; do
    echo "Processing container: $LXCHOSTNAME"

    # Stop the container
    echo "Stopping container $LXCHOSTNAME..."
    if ! lxc-stop -n "$LXCHOSTNAME"; then
        echo "Failed to stop container $LXCHOSTNAME"
        continue
    fi

    # Create a snapshot (using default directory)
    echo "Creating snapshot for $LXCHOSTNAME..."
    if ! lxc-snapshot -n "$LXCHOSTNAME"; then
        echo "Failed to create snapshot for $LXCHOSTNAME"
        # Optionally, start the container back up if snapshot fails
        lxc-start -n "$LXCHOSTNAME"
        continue
    fi

    # Start the container
    echo "Starting container $LXCHOSTNAME..."
    if ! lxc-start -n "$LXCHOSTNAME"; then
        echo "Failed to start container $LXCHOSTNAME"
        continue
    fi

    # List snapshots for the container
    echo "Listing snapshots for $LXCHOSTNAME..."
    lxc-snapshot -n "$LXCHOSTNAME" -L
    echo "----------------------------------"

    echo "Finished processing $LXCHOSTNAME"
    echo "=================================="
done

lxc-ls -f