#!/bin/bash
set -euo pipefail

echo "Actualizando..."
sudo apt update && sudo apt -y upgrade

echo "Instalando X11 + display manager..."
sudo apt install -y xorg xinit lightdm lightdm-gtk-greeter

echo "Instalando BSPWM y utilidades..."
sudo apt install -y curl bat lsd zsh bspwm dconf zsh-syntax-highlighting zsh-autosuggestions
sudo apt install -y kitty picom polybar ranger rofi sxhkd build-essential feh git

echo "Habilitando arranque gráfico..."
sudo systemctl enable lightdm
sudo systemctl set-default graphical.target

echo "Instalando fuentes..."
mkdir -p ~/.local/share/fonts
cp -r ./fonts/* ~/.local/share/fonts/ || true
fc-cache -f -v

echo "Fondo de pantalla..."
cp -f ./Wallpaper ~/

echo "Copiando configuración a ~/.config..."
mkdir -p ~/.config
cp -r ./config/* ~/.config/

echo "Asegurando permisos ejecutables..."
[ -f ~/.config/bspwm/bspwmrc ] && chmod +x ~/.config/bspwm/bspwmrc
[ -f ~/.config/sxhkd/sxhkdrc ] && chmod +x ~/.config/sxhkd/sxhkdrc

echo "Instalando Oh My Zsh (no interactivo)..."
export RUNZSH=no
export CHSH=no
if [ ! -d "$HOME/.oh-my-zsh" ]; then
  sh -c "$(curl -fsSL https://raw.githubusercontent.com/ohmyzsh/ohmyzsh/master/tools/install.sh)"
fi

echo "Instalando powerlevel10k..."
ZSH_CUSTOM="${ZSH_CUSTOM:-$HOME/.oh-my-zsh/custom}"
[ ! -d "$ZSH_CUSTOM/themes/powerlevel10k" ] && git clone --depth=1 https://github.com/romkatv/powerlevel10k.git "$ZSH_CUSTOM/themes/powerlevel10k"

echo "Copiando .zshrc (sin sudo) ..."
cp -f ./.zshrc ~/

echo "Instalando NeoVim y creando symlink..."
curl -LO https://github.com/neovim/neovim/releases/latest/download/nvim-linux-x86_64.tar.gz
sudo rm -rf /opt/nvim
sudo tar -C /opt -xzf nvim-linux-x86_64.tar.gz
sudo mv /opt/nvim-linux-x86_64 /opt/nvim
sudo ln -sf /opt/nvim/bin/nvim /usr/local/bin/nvim

echo "Copiando .screenlayout..."
cp -r ./.screenlayout ~/

echo "Creando ~/.xinitrc (por si arrancas con startx)..."
if [ ! -f ~/.xinitrc ]; then
  cat > ~/.xinitrc <<'EOF'
#!/bin/sh
pgrep -x sxhkd >/dev/null || sxhkd &
exec bspwm
EOF
  chmod +x ~/.xinitrc
fi

echo "Listo. Reinicia el sistema."

