#!/bin/bash

# Ensure the script is run with root privileges
if [ "$EUID" -ne 0 ]; then
  echo "Error: This script must be run as root. Please use sudo."
  exit 1
fi

REPO_FILE="/etc/yum.repos.d/cloudants-fedora.repo"

echo "=========================================="
echo " Setting up Cloudants Fedora Repository   "
echo "=========================================="

# 1. Write the repository configuration block
echo "Creating repository configuration file..."
cat << 'EOF' > "$REPO_FILE"
[cloudants-fedora-repo]
name=Cloudants Fedora Repository
baseurl=http://fedora-repository.cloudants.nl/x86_64/
enabled=1
gpgcheck=1
repo_gpgcheck=1
gpgkey=http://fedora-repository.cloudants.nl/RPM-GPG-KEY-custom
EOF

# 2. Set the appropriate permissions
chmod 644 "$REPO_FILE"
echo "Successfully created: $REPO_FILE"

# 3. Explicitly import the GPG key 
# This prevents Fedora from prompting the user to manually accept the key during the first package install
echo "Importing GPG key..."
rpm --import http://fedora-repository.cloudants.nl/RPM-GPG-KEY-custom

if [ $? -eq 0 ]; then
  echo "GPG key imported successfully."
else
  echo "Warning: Could not fetch or import GPG key. 'dnf' will attempt to fetch it dynamically later."
fi

# 4. Refresh package metadata
echo "Refreshing package manager cache..."
dnf clean all
dnf makecache --disablerepo="*" --enablerepo="cloudants-fedora-repo" -y

echo "------------------------------------------"
echo "Setup complete! The repository is active."
echo "=========================================="
