#!/bin/bash

# Lock file to avoid conflicts
> /var/lib/pacman/db.lck

# Change to the directory containing the pacman keyrings
cd /usr/share/pacman/keyrings

# Use all GPG files in the folder to generate a key list, excluding pubring.gpg and trustdb.gpg
key_list=""
for file in *.gpg; do
    if [[ $file != "pubring.gpg" && $file != "trustdb.gpg" ]]; then
        key_list+="${file%.gpg} "
    fi
done

# Initialize pacman keyring
pacman-key --init
if [ "$?" != "0" ]; then
    # If initialization fails, reset the keyring and create a new gpg.conf file
    > /var/lib/pacman/db.lck
    rm -R /etc/pacman.d/gnupg
    mkdir -p /etc/pacman.d/gnupg
    echo 'no-greeting
no-permission-warning
lock-never
keyserver-options timeout=10
keyserver-options import-clean
keyserver-options no-self-sigs-only
keyserver hkp://keyserver.ubuntu.com:80
keyserver hkps://pgp.mit.edu
keyserver hkps://keyserver.pgp.com
keyserver hkps://hkps.pool.sks-keyservers.net
keyserver hkps://keys.openpgp.org
keyserver hkps://keyserver.ubuntu.com' > /etc/pacman.d/gnupg/gpg.conf
    pacman-key --init
fi

# Re-lock the pacman database
> /var/lib/pacman/db.lck

# Populate the pacman keyring with keys from the generated key list
pacman-key --populate $key_list

if [ "$?" != "0" ]; then
    # If population fails, reset the keyring and retry
    > /var/lib/pacman/db.lck
    rm -R /etc/pacman.d/gnupg
    mkdir -p /etc/pacman.d/gnupg
    echo 'no-greeting
no-permission-warning
lock-never
keyserver-options timeout=10
keyserver-options import-clean
keyserver-options no-self-sigs-only
keyserver hkp://keyserver.ubuntu.com:80
keyserver hkps://pgp.mit.edu
keyserver hkps://keyserver.pgp.com
keyserver hkps://hkps.pool.sks-keyservers.net
keyserver hkps://keys.openpgp.org
keyserver hkps://keyserver.ubuntu.com' > /etc/pacman.d/gnupg/gpg.conf
    pacman-key --init
    pacman-key --populate $key_list
fi

# Remove the pacman database lock file to unlock pacman
rm /var/lib/pacman/db.lck
