#!/bin/sh
# Strict error handling: exit if any command fails
set -e

echo "====== Starting Yay Installation ======"

# 1. Guardrail: Ensure the user is running Arch Linux
if [ ! -f /etc/arch-release ]; then
    echo "ERROR: This script only supports Arch Linux." >&2
    exit 1
fi

# 2. Guardrail: Ensure the script is NOT run directly as root
# (makepkg will fail completely if run as root)
if [ "$(id -u)" -eq 0 ]; then
    echo "ERROR: Do not run this script as root/sudo directly." >&2
    echo "Run it as a normal user. The script will ask for sudo when needed." >&2
    exit 1
fi

# 3. Guardrail: Check for sudo access
if ! command -v sudo >/dev/null 2>&1; then
    echo "ERROR: 'sudo' is required to install dependencies. Please install sudo first." >&2
    exit 1
fi

# 4. Install prerequisites (base-devel and git) if missing
echo "Checking and installing required dependencies (base-devel, git)..."
sudo pacman -Sy --needed --noconfirm base-devel git

# 5. Create a clean, secure temporary directory
# Using mktemp ensures no overlapping folder issues in /tmp
TMP_DIR=$(mktemp -d /tmp/yay-build.XXXXXX)
echo "Created temporary directory at $TMP_DIR"

# Ensure cleanup happens even if the script crashes later
trap 'rm -rf "$TMP_DIR"' EXIT

# 6. Clone, Build, and Install
echo "Cloning yay-bin from the AUR..."
git clone https://aur.archlinux.org/yay-bin.git "$TMP_DIR"

echo "Navigating to build directory..."
cd "$TMP_DIR"

echo "Running makepkg to compile and install yay..."
# -s installs missing build dependencies via pacman
# -i installs the package once it's built
# --noconfirm bypasses prompts for easier automation
makepkg -si --noconfirm

echo "====== Yay successfully installed! ======"