#!/bin/bash

# Define the CentOS Vault base URL (use appropriate version and architecture)
VAULT_BASEURL="http://vault.centos.org/"

# Iterate over all repo files in /etc/yum.repos.d
# for repo_file in /etc/yum.repos.d/*.repo; do
#     if [ -f "$repo_file" ]; then
#         echo "Processing $repo_file..."

#         # Comment out any mirrorlist line
#         sudo sed -i 's/^mirrorlist=/#mirrorlist=/' "$repo_file"
        
#         # Replace any baseurl starting with http://mirror.centos.org/.* with the Vault base URL
#         sudo sed -i "s|^baseurl=http://mirror.centos.org/.*|baseurl=$VAULT_BASEURL|" "$repo_file"
        
#         # If there's no baseurl line, add the Vault base URL at the end of the file
#         if ! grep -q "^baseurl=" "$repo_file"; then
#             echo "baseurl=$VAULT_BASEURL" | sudo tee -a "$repo_file" > /dev/null
#         fi
#     fi
# done

echo "Completed updating all .repo files."

# Function to check network connectivity
check_network() {
    echo "Checking network connectivity..."
    if ping -c 4 8.8.8.8 &>/dev/null; then
        echo "Network is up!"
    else
        echo "Network is down. Please check your connection."
        exit 1
    fi
}

# Function to clean and update DNF cache
clean_and_update_cache() {
    echo "Cleaning DNF cache..."
    sudo dnf clean all
    sudo rm -rf /var/cache/dnf
    echo "Rebuilding DNF cache..."
    sudo dnf makecache
}

# Function to check if AppStream repo is enabled
check_appstream_repo() {
    echo "Checking if AppStream repository is enabled..."
    if sudo dnf repolist all | grep -i 'appstream' | grep -i 'enabled' &>/dev/null; then
        echo "AppStream repository is enabled."
    else
        echo "AppStream repository is not enabled. Enabling it now..."
        sudo dnf config-manager --set-enabled appstream
    fi
}

# Function to sync AppStream repository
sync_appstream_repo() {
    echo "Syncing AppStream repository..."
    sudo dnf --disablerepo="*" --enablerepo="appstream" update -y
}

# Function to perform a system update
perform_system_update() {
    echo "Performing system update..."
    sudo dnf update -y
}

# Main script execution
echo "Starting AppStream sync process..."

# Step 1: Check network connectivity
check_network

# Step 2: Clean and update DNF cache
clean_and_update_cache

# Step 3: Check if AppStream repo is enabled
check_appstream_repo

# Step 4: Sync AppStream repository
sync_appstream_repo

# Step 5: Perform a system-wide update
perform_system_update

echo "AppStream sync process completed!"