#!/bin/bash
# Fedora Setup Script - Replicates Arch dwm/zsh/nvim environment
# Run as your regular user (uses sudo when needed)

set -e

LOGFILE="$HOME/fedora-setup.log"
exec > >(tee -a "$LOGFILE") 2>&1

echo "Starting Fedora setup at $(date)"

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

info() { echo -e "${GREEN}[INFO]${NC} $1"; }
warn() { echo -e "${YELLOW}[WARN]${NC} $1"; }
error() { echo -e "${RED}[ERROR]${NC} $1"; exit 1; }

# Check if running as root
if [ "$EUID" -eq 0 ]; then
    error "Do not run this script as root. Run as your regular user."
fi

# Confirm before proceeding
echo "This script will install dwm, st, dmenu, neovim, zsh, and related tools."
echo "It will also configure your shell and window manager."
read -p "Continue? [y/N] " -n 1 -r
echo
if [[ ! $REPLY =~ ^[Yy]$ ]]; then
    exit 0
fi

# ============================================================================
# PHASE 1: Enable RPM Fusion and update system
# ============================================================================
info "Enabling RPM Fusion repositories..."
sudo dnf install -y \
    https://download1.rpmfusion.org/free/fedora/rpmfusion-free-release-$(rpm -E %fedora).noarch.rpm \
    https://download1.rpmfusion.org/nonfree/fedora/rpmfusion-nonfree-release-$(rpm -E %fedora).noarch.rpm || true

info "Updating system..."
sudo dnf update -y

# ============================================================================
# PHASE 2: Install packages
# ============================================================================
info "Installing core packages..."

# Development tools needed for building suckless software
DEVEL_PKGS="
    @development-tools
    libX11-devel
    libXft-devel
    libXinerama-devel
    freetype-devel
    fontconfig-devel
    harfbuzz-devel
    imlib2-devel
    libXrender-devel
"

# Terminal and shell
TERMINAL_PKGS="
    zsh
    alacritty
    tmux
"

# Editors and dev tools
DEV_PKGS="
    neovim
    git
    fzf
    ripgrep
    fd-find
    bat
    htop
    curl
    wget
    unzip
    rsync
    man-db
    man-pages
"

# X11 and window manager dependencies
X11_PKGS="
    xorg-x11-server-Xorg
    xorg-x11-xinit
    xorg-x11-xauth
    xorg-x11-drv-libinput
    xclip
    xdotool
    xprop
    xset
    xrandr
    autorandr
    picom
    dunst
    unclutter
    feh
    maim
    xwallpaper
    redshift
    light
"

# Fonts
FONT_PKGS="
    jetbrains-mono-fonts
    jetbrains-mono-nl-fonts
    google-noto-emoji-fonts
    google-noto-sans-cjk-fonts
    fontawesome-fonts
    dejavu-fonts-all
"

# Multimedia and utilities
UTIL_PKGS="
    pipewire
    pipewire-pulseaudio
    wireplumber
    mpd
    mpc
    mpv
    yt-dlp
    ffmpeg
    imagemagick
    zathura
    zathura-pdf-mupdf
    keepassxc
    firefox
"

# Container and cloud tools
CLOUD_PKGS="
    podman
    buildah
    skopeo
    kubectl
    helm
"

sudo dnf install -y $DEVEL_PKGS $TERMINAL_PKGS $DEV_PKGS $X11_PKGS $FONT_PKGS $UTIL_PKGS $CLOUD_PKGS

# Install Nerd Fonts (JetBrainsMono)
info "Installing JetBrainsMono Nerd Font..."
mkdir -p ~/.local/share/fonts
cd /tmp
if [ ! -f ~/.local/share/fonts/JetBrainsMonoNerdFont-Regular.ttf ]; then
    wget -q https://github.com/ryanoasis/nerd-fonts/releases/download/v3.1.1/JetBrainsMono.zip
    unzip -o JetBrainsMono.zip -d ~/.local/share/fonts/
    fc-cache -fv
fi

# ============================================================================
# PHASE 3: Build suckless software from source
# ============================================================================
info "Setting up suckless software..."

mkdir -p ~/.local/src

# dwm
info "Building dwm..."
cd ~/.local/src
if [ ! -d dwm ]; then
    git clone https://github.com/LukeSmithxyz/dwm.git
fi
cd dwm
sudo make clean install

# st (simple terminal)
info "Building st..."
cd ~/.local/src
if [ ! -d st ]; then
    git clone https://github.com/LukeSmithxyz/st.git
fi
cd st
sudo make clean install

# dmenu
info "Building dmenu..."
cd ~/.local/src
if [ ! -d dmenu ]; then
    git clone https://github.com/LukeSmithxyz/dmenu.git
fi
cd dmenu
sudo make clean install

# dwmblocks
info "Building dwmblocks..."
cd ~/.local/src
if [ ! -d dwmblocks ]; then
    git clone https://github.com/LukeSmithxyz/dwmblocks.git
fi
cd dwmblocks
sudo make clean install

# slock (screen locker)
info "Building slock..."
cd ~/.local/src
if [ ! -d slock ]; then
    git clone https://git.suckless.org/slock
fi
cd slock
sudo make clean install

# ============================================================================
# PHASE 4: Set up directory structure (XDG compliant)
# ============================================================================
info "Creating XDG directory structure..."

mkdir -p ~/.config/{zsh,x11,shell,dunst,alacritty,nvim,lf}
mkdir -p ~/.local/{bin,share,src}
mkdir -p ~/.local/bin/statusbar
mkdir -p ~/.cache

# ============================================================================
# PHASE 5: Configure zsh
# ============================================================================
info "Configuring zsh..."

# Install oh-my-zsh
if [ ! -d ~/.oh-my-zsh ]; then
    info "Installing oh-my-zsh..."
    sh -c "$(curl -fsSL https://raw.githubusercontent.com/ohmyzsh/ohmyzsh/master/tools/install.sh)" "" --unattended
fi

# Install powerlevel10k
if [ ! -d ~/.oh-my-zsh/custom/themes/powerlevel10k ]; then
    info "Installing powerlevel10k..."
    git clone --depth=1 https://github.com/romkatv/powerlevel10k.git ~/.oh-my-zsh/custom/themes/powerlevel10k
fi

# Install zsh-fast-syntax-highlighting
if [ ! -d ~/.oh-my-zsh/custom/plugins/fast-syntax-highlighting ]; then
    info "Installing fast-syntax-highlighting..."
    git clone https://github.com/zdharma-continuum/fast-syntax-highlighting.git ~/.oh-my-zsh/custom/plugins/fast-syntax-highlighting
fi

# Create zprofile
cat > ~/.zprofile << 'EOF'
#!/bin/sh

# Add all directories in ~/.local/bin to $PATH
export PATH="$PATH:$(find ~/.local/bin -type d | paste -sd ':' -)"

unsetopt PROMPT_SP 2>/dev/null

# Default programs
export EDITOR="nvim"
export TERMINAL="alacritty"
export TERMINAL_PROG="alacritty"
export BROWSER="firefox"

# XDG directories
export XDG_CONFIG_HOME="$HOME/.config"
export XDG_DATA_HOME="$HOME/.local/share"
export XDG_CACHE_HOME="$HOME/.cache"
export XINITRC="$XDG_CONFIG_HOME/x11/xinitrc"
export ZDOTDIR="$XDG_CONFIG_HOME/zsh"
export HISTFILE="$XDG_DATA_HOME/history"
export CARGO_HOME="$XDG_DATA_HOME/cargo"
export GOPATH="$XDG_DATA_HOME/go"
export GOMODCACHE="$XDG_CACHE_HOME/go/mod"

# Other settings
export FZF_DEFAULT_OPTS="--layout=reverse --height 40%"
export LESS="R"
export QT_QPA_PLATFORMTHEME="gtk2"
export MOZ_USE_XINPUT2=1
export _JAVA_AWT_WM_NONREPARENTING=1

# Start X on tty1
[ "$(tty)" = "/dev/tty1" ] && ! pidof -s Xorg >/dev/null 2>&1 && exec startx "$XINITRC"
EOF

# Create zshrc
cat > ~/.config/zsh/.zshrc << 'EOF'
# Enable Powerlevel10k instant prompt
if [[ -r "${XDG_CACHE_HOME:-$HOME/.cache}/p10k-instant-prompt-${(%):-%n}.zsh" ]]; then
  source "${XDG_CACHE_HOME:-$HOME/.cache}/p10k-instant-prompt-${(%):-%n}.zsh"
fi

export SHELL="/bin/zsh"

# Enable colors
autoload -U colors && colors
setopt autocd
setopt interactive_comments

# History settings
HISTSIZE=10000000
SAVEHIST=10000000
HISTFILE=~/.zsh_history
setopt APPEND_HISTORY
setopt EXTENDED_HISTORY
setopt HIST_VERIFY
setopt SHARE_HISTORY
setopt INC_APPEND_HISTORY
setopt HIST_EXPIRE_DUPS_FIRST
setopt HIST_IGNORE_DUPS
setopt HIST_FIND_NO_DUPS
setopt HIST_REDUCE_BLANKS

# Tab completion
autoload -U compinit -C
zstyle ':completion:*' menu select
zmodload zsh/complist
compinit -C
_comp_options+=(globdots)

# vi mode
bindkey -v
export KEYTIMEOUT=1

# Vim keys in tab complete menu
bindkey -M menuselect 'h' vi-backward-char
bindkey -M menuselect 'k' vi-up-line-or-history
bindkey -M menuselect 'l' vi-forward-char
bindkey -M menuselect 'j' vi-down-line-or-history
bindkey -v '^?' backward-delete-char

# Cursor shape for vi modes
function zle-keymap-select () {
    case $KEYMAP in
        vicmd) echo -ne '\e[1 q';;
        viins|main) echo -ne '\e[5 q';;
    esac
}
zle -N zle-keymap-select
zle-line-init() { zle -K viins; echo -ne "\e[5 q"; }
zle -N zle-line-init
echo -ne '\e[5 q'
preexec() { echo -ne '\e[5 q'; }

# Useful keybindings
bindkey -s '^f' 'cd "$(dirname "$(fzf)")"\n'
bindkey '^[[P' delete-char
autoload edit-command-line; zle -N edit-command-line
bindkey '^e' edit-command-line
bindkey '^R' history-incremental-search-backward

export GPG_TTY=$(tty)

# oh-my-zsh
export ZSH="$HOME/.oh-my-zsh"
ZSH_THEME="powerlevel10k/powerlevel10k"

plugins=(
    git
    kubectl
    fast-syntax-highlighting
)

source $ZSH/oh-my-zsh.sh

# Aliases
[ -f "${XDG_CONFIG_HOME:-$HOME/.config}/shell/aliasrc" ] && source "${XDG_CONFIG_HOME:-$HOME/.config}/shell/aliasrc"

# PATH
export PATH="${KREW_ROOT:-$HOME/.krew}/bin:$PATH"
export PATH=$PATH:$HOME/bin
export PATH=$PATH:$HOME/.local/bin
export PATH=$PATH:$HOME/.local/bin/statusbar
export PATH=$PATH:$GOPATH/bin
export PATH=$PATH:~/.local/share/cargo/bin

# p10k config
[[ ! -f ~/.config/zsh/.p10k.zsh ]] || source ~/.config/zsh/.p10k.zsh
typeset -g POWERLEVEL9K_INSTANT_PROMPT=quiet
EOF

# Create shell aliases
cat > ~/.config/shell/aliasrc << 'EOF'
#!/bin/sh

# Use neovim for vim
[ -x "$(command -v nvim)" ] && alias vim="nvim" vimdiff="nvim -d"

# sudo for common system commands
for command in mount umount sv dnf updatedb su shutdown poweroff reboot; do
    alias $command="sudo $command"
done; unset command

# Verbosity and safety
alias cp="cp -iv"
alias mv="mv -iv"
alias rm="rm -vI"
alias bc="bc -ql"
alias rsync="rsync -vrPlu"
alias mkd="mkdir -pv"
alias yt="yt-dlp --embed-metadata -i"
alias yta="yt -x -f bestaudio/best"
alias ffmpeg="ffmpeg -hide_banner"

# Colorize
alias ls="ls -hN --color=auto --group-directories-first"
alias grep="grep --color=auto"
alias diff="diff --color=auto"
alias ip="ip -color=auto"

# Abbreviations
alias ka="killall"
alias g="git"
alias sdn="shutdown -h now"
alias e="nvim"
alias v="nvim"
alias p="sudo dnf"
alias z="zathura"
EOF

# ============================================================================
# PHASE 6: Configure X11 and dwm
# ============================================================================
info "Configuring X11..."

# xinitrc
cat > ~/.config/x11/xinitrc << 'EOF'
#!/bin/sh

if [ -f "${XDG_CONFIG_HOME:-$HOME/.config}/x11/xprofile" ]; then
    . "${XDG_CONFIG_HOME:-$HOME/.config}/x11/xprofile"
else
    . "$HOME/.xprofile"
fi

dbus-update-activation-environment --all
exec dbus-launch ssh-agent dwm
EOF
chmod +x ~/.config/x11/xinitrc

# xprofile
cat > ~/.config/x11/xprofile << 'EOF'
#!/bin/sh

xrandr --dpi 96
xset r rate 300 50 &
setxkbmap -option compose:caps &

# Set background (create setbg script or use feh)
[ -f ~/.config/wall.png ] && feh --bg-scale ~/.config/wall.png &

# Autostart programs
autostart="dunst unclutter pipewire"
for program in $autostart; do
    pidof -sx "$program" || "$program" &
done >/dev/null 2>&1
EOF
chmod +x ~/.config/x11/xprofile

# Create symlink for startx compatibility
ln -sf ~/.config/x11/xinitrc ~/.xinitrc

# ============================================================================
# PHASE 7: Configure Alacritty
# ============================================================================
info "Configuring Alacritty..."

cat > ~/.config/alacritty/alacritty.toml << 'EOF'
[env]
WINIT_X11_SCALE_FACTOR = "1.0"

[font]
size = 11

[font.normal]
family = "JetBrainsMono Nerd Font"
style = "Regular"

[font.bold]
family = "JetBrainsMono Nerd Font"
style = "Bold"

[font.italic]
family = "JetBrainsMono Nerd Font"
style = "Italic"

[window]
padding = { x = 8, y = 8 }
decorations = "None"
opacity = 1.0

[cursor]
style = { shape = "Block", blinking = "Off" }

# Gruvbox Dark
[colors.primary]
background = "#1d2021"
foreground = "#ebdbb2"

[colors.normal]
black   = "#3c3836"
red     = "#cc241d"
green   = "#98971a"
yellow  = "#d79921"
blue    = "#458588"
magenta = "#b16286"
cyan    = "#689d6a"
white   = "#a89984"

[colors.bright]
black   = "#928374"
red     = "#fb4934"
green   = "#b8bb26"
yellow  = "#fabd2f"
blue    = "#83a598"
magenta = "#d3869b"
cyan    = "#8ec07c"
white   = "#ebdbb2"
EOF

# ============================================================================
# PHASE 8: Configure Dunst
# ============================================================================
info "Configuring Dunst..."

cat > ~/.config/dunst/dunstrc << 'EOF'
[global]
    monitor = 0
    follow = keyboard
    width = 370
    height = 350
    offset = 0x19
    padding = 2
    horizontal_padding = 2
    transparency = 25
    font = JetBrainsMono Nerd Font 11
    format = "<b>%s</b>\n%b"

[urgency_low]
    background = "#1d2021"
    foreground = "#928374"
    timeout = 3

[urgency_normal]
    foreground = "#ebdbb2"
    background = "#458588"
    timeout = 5

[urgency_critical]
    background = "#cc241d"
    foreground = "#ebdbb2"
    frame_color = "#fabd2f"
    timeout = 10
EOF

# ============================================================================
# PHASE 9: Create utility scripts
# ============================================================================
info "Creating utility scripts..."

# setbg - set wallpaper
cat > ~/.local/bin/setbg << 'EOF'
#!/bin/sh
# Sets the wallpaper
wall="${1:-$HOME/.config/wall.png}"
[ -f "$wall" ] && feh --bg-scale "$wall"
EOF
chmod +x ~/.local/bin/setbg

# ============================================================================
# PHASE 10: Configure Neovim
# ============================================================================
info "Setting up Neovim..."

# Create basic init.lua if doesn't exist
if [ ! -f ~/.config/nvim/init.lua ]; then
    cat > ~/.config/nvim/init.lua << 'EOF'
-- Bootstrap lazy.nvim
local lazypath = vim.fn.stdpath("data") .. "/lazy/lazy.nvim"
if not vim.loop.fs_stat(lazypath) then
  vim.fn.system({
    "git", "clone", "--filter=blob:none",
    "https://github.com/folke/lazy.nvim.git",
    "--branch=stable", lazypath,
  })
end
vim.opt.rtp:prepend(lazypath)

-- Basic options
vim.g.mapleader = ","
vim.opt.number = true
vim.opt.relativenumber = true
vim.opt.tabstop = 4
vim.opt.shiftwidth = 4
vim.opt.expandtab = true
vim.opt.clipboard = "unnamedplus"
vim.opt.splitbelow = true
vim.opt.splitright = true
vim.opt.ignorecase = true
vim.opt.smartcase = true
vim.opt.termguicolors = true

-- Load plugins
require("lazy").setup({
  { "folke/tokyonight.nvim", lazy = false, priority = 1000 },
  { "nvim-treesitter/nvim-treesitter", build = ":TSUpdate" },
  { "nvim-telescope/telescope.nvim", dependencies = { "nvim-lua/plenary.nvim" } },
  { "neovim/nvim-lspconfig" },
  { "hrsh7th/nvim-cmp" },
  { "hrsh7th/cmp-nvim-lsp" },
  { "lewis6991/gitsigns.nvim" },
  { "nvim-tree/nvim-tree.lua" },
  { "nvim-lualine/lualine.nvim" },
})

vim.cmd.colorscheme("tokyonight")
EOF
fi

# ============================================================================
# PHASE 11: Set default shell to zsh
# ============================================================================
info "Setting zsh as default shell..."
if [ "$SHELL" != "/bin/zsh" ]; then
    chsh -s /bin/zsh
fi

# ============================================================================
# PHASE 12: Create dwm session for display managers
# ============================================================================
info "Creating dwm desktop session..."

sudo tee /usr/share/xsessions/dwm.desktop > /dev/null << 'EOF'
[Desktop Entry]
Encoding=UTF-8
Name=dwm
Comment=Dynamic window manager
Exec=/usr/local/bin/dwm
Icon=dwm
Type=XSession
EOF

# ============================================================================
# Done
# ============================================================================
echo ""
info "Setup complete!"
echo ""
echo "Next steps:"
echo "  1. Log out of GNOME"
echo "  2. At the login screen, click the gear icon and select 'dwm'"
echo "  3. Log in - you'll be in dwm"
echo ""
echo "Or, from a TTY (Ctrl+Alt+F2):"
echo "  1. Log in"
echo "  2. Run 'startx' to start dwm"
echo ""
echo "Key bindings in dwm (Mod key is Super/Windows key):"
echo "  Mod+Enter     - Open terminal (alacritty)"
echo "  Mod+d         - Open dmenu"
echo "  Mod+j/k       - Focus windows"
echo "  Mod+Shift+c   - Close window"
echo "  Mod+Shift+q   - Quit dwm"
echo "  Mod+1-9       - Switch workspaces"
echo ""
echo "Log file: $LOGFILE"
