#!/bin/bash

# Read the dist/packages.txt and install packages using pacman

PACKAGES_FILE="dist/packages.txt"

if [ ! -f "$PACKAGES_FILE" ]; then
    echo "Packages file not found: $PACKAGES_FILE"
    exit 1
else
    mapfile -t packages < "$PACKAGES_FILE"
    pacman -Syu --noconfirm "${packages[@]}"
fi

# Set arch-specific packages like Java version
archlinux-java set java-21-openjdk # Use the version you installed

ARCH_PACKAGE_FILE="dist/arch/packages.txt"

if [ ! -f "$ARCH_PACKAGE_FILE" ]; then
    echo "Arch-specific packages file not found: $ARCH_PACKAGE_FILE"
    exit 1
else
    mapfile -t arch_packages < "$ARCH_PACKAGE_FILE"
    pacman -Syu --noconfirm "${arch_packages[@]}"
fi

if command -v paru &> /dev/null; then
    echo "paru is already installed. Reinstalling..."
else
    git clone https://aur.archlinux.org/paru.git
    cd paru
    
    # Check if $USER is root and if so add a temporary non-root user for building paru
    if [ "$EUID" -eq 0 ]; then
        echo "Building paru as root is not allowed. Creating a temporary user for building..."
        TEMP_USER="builder"
        useradd -m "$TEMP_USER"
        # add user to sudoers with no password
        echo "$TEMP_USER ALL=(ALL) NOPASSWD: ALL" >> /etc/sudoers
        groupadd sudo
        usermod -aG wheel "$TEMP_USER"
        usermod -aG sudo "$TEMP_USER"

        echo "Adding temporary user pwd"
        yes | passwd -d "$TEMP_USER"
        chown -R "$TEMP_USER":"$TEMP_USER" .
        echo "Building paru as user $TEMP_USER..."
        yes | su - "$TEMP_USER" -c "cd $(pwd) && makepkg -si --noconfirm"
    else
        echo "Building paru as user $USER..."
        makepkg -si --noconfirm
    fi
    
    cd ..
    rm -rf paru
fi

PARU_PACKAGE_FILE="dist/arch/paru.txt"

# check if Root user or TEMP_USER exists

if [ "$EUID" -eq 0 ]; then
    BUILD_USER="$TEMP_USER"
else
    BUILD_USER="$USER"
fi

if [ ! -f "$PARU_PACKAGE_FILE" ]; then
    echo "Paru-specific packages file not found: $PARU_PACKAGE_FILE"
    exit 1
else
    mapfile -t paru_packages < "$PARU_PACKAGE_FILE"
    echo "Installing AUR packages using paru as user $BUILD_USER..."
    yes | su - "$BUILD_USER" -c "paru -S --noconfirm ${paru_packages[*]}"
    yes | su - "$BUILD_USER" -c "yes | /opt/android-sdk/cmdline-tools/latest/bin/sdkmanager --licenses"
    yes | su - "$BUILD_USER" -c "yes | sudo pacman -Syu --noconfirm gradle"
fi

echo "All packages installed successfully."
