#!/bin/bash

# Path to the apt-mirror mirror directory
MIRROR_PATH="/media/apt/mirror"

# Directory to store temporary files
TEMP_DIR="/media/apt/temp"

# Create the temporary directory if it doesn't exist
mkdir -p "$TEMP_DIR"

# Start the cleaning process
echo "Starting cleanup of the apt-mirror directory: $MIRROR_PATH"

# Loop through each repository in the mirror.list
for repo in $(grep -oP '(?<=deb\s)(http.*?)(?=\s)' /etc/apt/mirror.list | uniq); do
    echo "Checking repository: $repo"

    # Fetch the list of currently available packages
    wget -q -r -l1 --no-parent -nd -A .deb "$repo" -P "$TEMP_DIR"

    # Remove files not present in the temp directory
    cd "$MIRROR_PATH" || exit
    find . -type f ! -name "$(basename -a $TEMP_DIR/*)" -exec rm -f {} \;

    # Cleanup temporary files
    rm -rf "$TEMP_DIR/*"
done

echo "Cleanup complete."
