#!/bin/bash
set -e
source "$(dirname "${BASH_SOURCE[0]}")/../lib/logging.sh"

log "Starting Niri installer (scrollable-tiling Wayland compositor)..."

# 1. Update system and install Flatpak
log "Updating system and installing Flatpak..."
sudo pacman -Syu --noconfirm --needed flatpak

# 2. Install required packages
log "Installing required packages..."
sudo pacman -Syu --noconfirm --needed \
    niri xdg-desktop-portal-gnome wl-clipboard swaybg swaylock swayidle \
    xfce-polkit gammastep \
    wofi kitty dunst \
    nwg-drawer nwg-menu nwg-look \
    python cmake meson cpio pkgconf ruby-pkg-config \
    nm-connection-editor network-manager-applet blueman bluez \
    pipewire alsa-utils firefox greetd-tuigreet \
    grim slurp gst-plugin-pipewire imagemagick \
    nerd-fonts otf-font-awesome \
    pipewire-alsa pipewire-jack pipewire-pulse \
    qt5-wayland qt6-wayland swww ttf-jetbrains-mono wireplumber \
    xdg-utils xorg-xinit papirus-icon-theme \
    cool-retro-term qalculate-gtk iwd dbus \
    thunar tumbler thunar-archive-plugin thunar-shares-plugin thunar-volman \
    pcmanfm-qt udisks2 ly kew \
    pavucontrol playerctl wf-recorder sound-theme-freedesktop \
    xinput jq python-opencv v4l-utils

# 3. Enable essential services
log "Enabling essential services..."
enable_service NetworkManager.service
sudo systemctl disable getty@tty1.service || true
# Disable greetd, which core.sh enables by default for every install. niri uses
# ly as its greeter, so leaving greetd enabled means two display managers both
# race to claim tty1 — and the stale greetd/tuigreet greeter can win, showing the
# old text login instead of ly. Disable it so ly is the sole greeter.
disable_service greetd.service
enable_service ly@tty1.service
enable_service udisks2.service

# 4. Install AUR packages
log "Installing AUR packages..."
rustup default stable
yay -Syu --answerdiff None --answerclean All --noconfirm --needed \
    vicinae-bin bluetuith wvkbd iwmenu pinta \
    walker-bin ulauncher bzmenu udiskie \
    wofi-calc bri chamel

# 5. EWW bar selection and compilation
log "Setting up EWW bar..."
rm -rf ~/.config/eww
# Skip the form-factor prompt in unattended installs (answerfile mode) or when
# stdin is not a terminal; default to the desktop/no-battery layout so the
# install never blocks waiting for a keypress.
if [[ "${MARCHY_UNATTENDED:-0}" == "1" || ! -t 0 ]]; then
    doit="P"
    log "Unattended mode — installing desktop (no-battery) EWW bar."
else
    read -n1 -p "Install eww bar for PC, Notebook or Tablet [P/N/T]: " doit
    echo
fi
case $doit in
    n|N) cp -rf ~/Dotfiles/desktopenvs/niri/eww/ ~/.config/ ;;
    p|P) cp -rf ~/Dotfiles/desktopenvs/niri/eww-nobattery/ ~/.config/eww ;;
    t|T) cp -rf ~/Dotfiles/desktopenvs/niri/eww-touch/ ~/.config/eww ;;
    *)   warn "No valid choice — skipping EWW copy. Run manually later." ;;
esac

log "Compiling EWW..."
mkdir -p ~/install-tmp
cd ~/install-tmp
git clone https://github.com/elkowar/eww
cd eww
cargo build --release --no-default-features --features=wayland
chmod +x target/release/eww
sudo cp target/release/eww /usr/bin/
cd ~

# 6. Theme and icon setup
log "Installing themes and icons..."
sudo cp -r ~/Dotfiles/gtk-themes/cyberqueer /usr/share/themes
sudo cp ~/Dotfiles/desktopenvs/niri/btop/themes/cyberqueer.theme /usr/share/btop/themes
sudo cp -f ~/Dotfiles/etc-ly-config.ini /etc/ly/config.ini
sudo ln -sf /usr/bin/kitty /usr/bin/xdg-terminal-exec
if have_user_bus; then
    gsettings set org.gnome.desktop.interface color-scheme 'prefer-dark' || true
else
    skip "No session bus — set GNOME color-scheme to dark after first login."
fi

# 7. Cursor setup
log "Installing cursor theme..."
mkdir -p ~/.icons
curl -fL -o ~/install-tmp/Nordzy-cursors-lefthand.tar.gz \
    https://github.com/guillaumeboehm/Nordzy-cursors/releases/download/v2.3.0/Nordzy-cursors-lefthand.tar.gz
tar -zxf ~/install-tmp/Nordzy-cursors-lefthand.tar.gz -C ~/.icons/

# 8. Enable Bluetooth and wireless services
log "Enabling Bluetooth and wireless services..."
enable_service bluez
enable_service bluetooth.service
enable_service iwd.service

# 9. Copy configs
log "Copying configs..."
CONFIGS=(kitty mimeapps.list vicinae walker ulauncher niri nwg-drawer nwg-panel wofi dunst alacritty scripts btop gtk-3.0 waybar xfce4)
for cfg in "${CONFIGS[@]}"; do
    rm -rf ~/.config/"$cfg"
    cp -rL ~/Dotfiles/desktopenvs/niri/"$cfg" ~/.config/
done

# Vicinae loads NAMED custom themes only from ~/.local/share/vicinae/themes/*.toml,
# NOT from ~/.config/vicinae/. The cyberqueer.toml copied above (niri/vicinae is a
# symlink to hyprlua/vicinae) lands in the config dir where Vicinae never looks, so
# settings.json's theme.dark.name="cyberqueer" silently falls back to the stock
# dark theme. Deploy the theme where Vicinae actually scans so it resolves.
mkdir -p ~/.local/share/vicinae/themes
cp -f ~/Dotfiles/desktopenvs/niri/vicinae/cyberqueer.toml \
      ~/.local/share/vicinae/themes/cyberqueer.toml

cp ~/Dotfiles/colors.conf ~/.config/colors.conf

# 10. Wallpaper and resources
log "Copying wallpaper and resources..."
mkdir -p ~/Pictures ~/Pictures/Screenshots
cp ~/Dotfiles/resources/fflogo.svg ~/Pictures/fflogo.svg
curl -fL "https://cloud.abdelbaki.eu/apps/theming/image/background?v=15" -o ~/Pictures/background.jpg

# 12. Python venv for scripts
log "Setting up Python venv for scripts..."
python -m venv ~/.config/python-script
~/.config/python-script/bin/pip install speedtest-cli requests pint simpleeval parsedatetime

# 13. Udiskie icon fix
log "Applying Udiskie icon fix..."
PAPIRUS_DIR="/usr/share/icons/Papirus-Dark/status"
HICOLOR_DIR="/usr/share/icons/hicolor/scalable/status"
if [ -d "$PAPIRUS_DIR" ]; then
    sudo ln -sf "$PAPIRUS_DIR/checkbox-checked.svg"   "$HICOLOR_DIR/udiskie-checkbox-checked.svg"
    sudo ln -sf "$PAPIRUS_DIR/checkbox-unchecked.svg" "$HICOLOR_DIR/udiskie-checkbox-unchecked.svg"
    sudo gtk-update-icon-cache -f -t /usr/share/icons/hicolor
else
    warn "Papirus-Dark not found — skipping udiskie icon fix."
fi

# 14. Enable udiskie
log "Enabling udiskie service..."
enable_service udiskie.service
start_service udiskie.service

# 15. Make scripts executable
log "Setting script permissions..."
chmod +x ~/.config/scripts/*.sh ~/.config/scripts/activewindow \
         ~/.config/scripts/wallpaper-picker ~/.config/scripts/windowswitcher \
         ~/.config/scripts/workspace ~/.config/scripts/workspacefocus/*.sh \
         ~/.config/scripts/toggle-layout.sh ~/.config/scripts/timer-pick \
         ~/.config/scripts/timer-run ~/.config/scripts/ulwatchdog.sh \
         2>/dev/null || true

# 16. Install config updater and theme script
log "Installing config updater and theme script..."
mkdir -p ~/.config/config-updater
ln -sf ~/Dotfiles/desktopenvs/niri/config-updater/updater.conf ~/.config/config-updater/updater.conf
ln -sf ~/Dotfiles/desktopenvs/niri/config-updater/update-configs.sh ~/update-configs.sh
cp ~/Dotfiles/apply-theme.sh ~/apply-theme.sh
chmod +x ~/apply-theme.sh

log "Niri installation complete. Reboot to start."
