#!/bin/bash
set -euo pipefail

# Parse command line arguments
while [[ $# -gt 0 ]]; do
    key="$1"
    case "$key" in
        --image)
            IMAGE_NAME="$2"
            shift
            shift
            ;;
        *)
            echo "Error: Unknown option: $key"
            echo "Usage: $0 --image IMAGE_NAME"
            exit 1
            ;;
    esac
done

# Define the path to the temporary directory where the files will be extracted
DESTINATION="/tmp/docker_images/${IMAGE_NAME}"
MANIFEST="${DESTINATION}/manifest.json"

# Define a function to download and extract the Docker image layers
function extract_docker_image {
    # Pull image to make sure we have it before we save it.
    docker pull "$IMAGE_NAME"

    # Save the Docker image as a tar file
    echo "Saving Docker image as a tar file..." >&2
    docker save "$1" -o "${DESTINATION}/image.tar"

    # Extract the Docker image layers to the destination directory
    echo "Extracting Docker image layers..." >&2
    mkdir -p "${DESTINATION}/layers"
    tar -xf "${DESTINATION}/image.tar" -C "${DESTINATION}/"

    # Rename the layer directories to their respective layer IDs
    LAYERS=$(jq -r '.[0].Layers[]' "${MANIFEST}")

    # Extract each layer
    for LAYER in ${LAYERS}; do
      BLOB="${LAYER}"
      # Extract the layer tar file to the destination directory
      echo "Extracting layer ${LAYER}..." >&2
      mkdir -p "${DESTINATION}/$(dirname ${BLOB})"
      tar -xf "${DESTINATION}/${BLOB}" -C "${DESTINATION}/layers"
      echo "Layer ${LAYER} extracted" >&2
    done
}

# Ensure that the user has provided the Docker image name using the --image flag
if [ -z "$IMAGE_NAME" ]; then
    echo "Error: Docker image name not provided." >&2
    echo "Usage: $0 --image IMAGE_NAME" >&2
    exit 1
fi

# Create the destination directory if it doesn't already exist
rm -rf "${DESTINATION}"
mkdir -p "${DESTINATION}"

# Call the function to download and extract the Docker image layers
extract_docker_image "$IMAGE_NAME"

