#!/usr/bin/env bash
set -e

# ---- Permissions for Steam / Flatpak (assumes UID 1000) ----
sudo chown -R 1000:1000 /mnt/game_drive

# Steam will automatically detect /mnt/game_drive as a library path
# XIVLauncher (Flatpak) needs filesystem access
flatpak override --user --filesystem=/mnt/game_drive dev.goats.xivlauncher

# ---- Install xrandr ----
sudo dnf -y install xrandr

# ---- Disable compositor, fix window flickering with Nvidia ----
xfconf-query -c xfwm4 -p /general/use_compositing -s false

# ---- Install gamemode ----
sudo dnf -y install gamemode gamemode-devel
# gamemoded -t

# ---- Disable unneeded services ----
sudo systemctl disable --now \
  bluetooth.service \
  ModemManager.service \
  cups.service \
  avahi-daemon.service \
  chronyd.service \
  NetworkManager-wait-online.service \
  geoclue.service \
  smartd.service \
  upower.service

# ---- Build & install ananicy-cpp ----
# ---- Install build tools (idempotent) ----
sudo dnf -y install @development-tools
sudo dnf -y install cmake systemd-devel spdlog-devel fmt-devel nlohmann-json-devel make automake gcc gcc-c++

# ---- Clone ananicy-cpp only if not present ----
if [ ! -d "$HOME/ananicy-cpp" ]; then
  git clone https://gitlab.com/ananicy-cpp/ananicy-cpp.git "$HOME/ananicy-cpp"
fi

# ---- Build and install ----
cd "$HOME/ananicy-cpp"

# Only create build dir if it doesn't exist
mkdir -p build
cd build

# Re-run cmake safely
cmake -DCMAKE_BUILD_TYPE=Release ..

# Build only if necessary
make -j$(nproc)

# Install idempotently
sudo make install

# Enable service safely
sudo systemctl enable ananicy-cpp || true
sudo systemctl start ananicy-cpp || true

# ---- CachyOS performance packages ----
sudo dnf -y copr enable bieszczaders/kernel-cachyos-addons
sudo dnf -y install cachyos-ksm-settings scx-scheds

# ---- Configure SCX scheduler (bpfland, gaming) ----
sudo mkdir -p /etc/scx_loader
sudo tee /etc/scx_loader/config.toml >/dev/null <<'EOF'
default_sched = "scx_bpfland"
default_mode = "Gaming"

[scheds.scx_bpfland]
auto_mode = []
gaming_mode = ["-m", "performance"]
lowlatency_mode = ["-s", "5000", "-S", "500", "-l", "5000", "-m", "performance"]
powersave_mode = ["-m", "powersave"]
EOF

sudo systemctl enable --now scx_loader

# ---- Enable TRIM ----
sudo systemctl enable --now fstrim.timer

# ---- Cleanup ----
sudo dnf clean all
sudo journalctl --vacuum-time=7d
sudo journalctl --vacuum-size=100M

echo "Post-reboot configuration complete."