#!/bin/bash

# Save original language settings
original_lc_all=$LC_ALL
original_lang=$LANG

# Force English locale
#export LC_ALL=en_US.UTF-8
export LANG=en_US.UTF-8

# List of packages
packages="wget curl git xdg-utils xdg-user-dirs build-essential htop dkms cmake plymouth plymouth-themes power-profiles-daemon python3 wayland-protocols wayland-utils wlr-randr libwlroots-0.18"

# Directory to store downloaded packages
download_dir="$(pwd)/iso-extract/src/packages"
#download_dir="packages-download"

# Create the download directory if it doesn't exist
#sudo mkdir -p "$download_dir"
#sudo chmod -R 777 "$download_dir"

sudo mkdir -p "$download_dir"/archives/partial
sudo chmod -R 777 "$download_dir"
#sudo chmod -R 644 "$download_dir"
sudo chown root:root "$download_dir"

#sudo chmod 755 "$download_dir"/archives/
sudo chown root:root "$download_dir"/archives/

#sudo chmod 777 "$download_dir"/archives/partial
sudo chown -R _apt:root "$download_dir"/archives/partial
sudo chmod -R 777 "$download_dir"/archives/partial

sudo apt update
#sudo apt reinstall --download-only -y -o Dir::Cache="./" -o Dir::Cache::archives="$download_dir" "$packages"

# Loop through each package
for package in $packages; do
  echo "Getting: $package"
  sudo apt reinstall --download-only -y -o Dir::Cache="$download_dir" "$package"
  echo "Getting dependencies for: $package"
  # Get the list of dependencies
  dependencies=$(apt-cache depends "$package" 2>/dev/null | grep -oP '(?<=Depends: ).*' | tr ',' '\n' | sed 's/ //g')
  # Download each dependency
  for dependency in $dependencies; do
    echo "  Downloading: $dependency"
    sudo apt reinstall --download-only -y -o Dir::Cache="$download_dir" "$dependency"
  done
done

sudo chmod -R 777 "$download_dir"

echo "Packages and Dependencies downloaded to: $download_dir"
ls "$download_dir"

# Restore original language settings
#export LC_ALL="$original_lc_all"
export LANG="$original_lang"
