#!/usr/bin/env bash
set -euo pipefail

log() { printf "\n==> %s\n" "$*"; }
have() { command -v "$1" >/dev/null 2>&1; }

DOTFILES_REPO="https://code.lab.unbl.ink/secstate/dotfiles"
DOTFILES_DIR="${DOTFILES_DIR:-$HOME/.dotfiles}"
OMZ_DIR="${ZSH:-$HOME/.oh-my-zsh}"
DOOM_DIR="${DOOM_DIR:-$HOME/.emacs.d}"
BACKUP_DIR="$HOME/.backup"

OS="$(uname -s)"
PLATFORM=""

# -------- Detect platform --------
if [[ "$OS" == "Darwin" ]]; then
	PLATFORM="macos"
elif [[ "$OS" == "FreeBSD" ]]; then
	PLATFORM="freebsd"
elif [[ "$OS" == "Linux" ]]; then
	if [[ -r /etc/os-release ]]; then
		# shellcheck disable=SC1091
		. /etc/os-release
	fi

	is_arch=0
	case "${ID:-}" in
	arch | endeavouros) is_arch=1 ;;
	esac
	if [[ $is_arch -eq 0 && -n "${ID_LIKE:-}" ]] && echo "$ID_LIKE" | grep -qi arch; then
		is_arch=1
	fi

	is_fedora=0
	case "${ID:-}" in
	fedora) is_fedora=1 ;;
	esac
	if [[ $is_fedora -eq 0 && -n "${ID_LIKE:-}" ]] && echo "$ID_LIKE" | grep -qiE 'fedora|rhel'; then
		is_fedora=1
	fi

	if [[ $is_arch -eq 1 ]]; then
		PLATFORM="arch"
	elif [[ $is_fedora -eq 1 ]]; then
		PLATFORM="fedora"
	else
		echo "Unsupported Linux distro (ID=${ID:-unknown}, ID_LIKE=${ID_LIKE:-unknown})."
		exit 1
	fi
else
	echo "Unsupported OS: $OS"
	exit 1
fi

# -------- Install basics (git, stow, zsh, curl, make) --------
install_arch() {
	log "Installing prerequisites (Arch/EndeavourOS)..."
	sudo pacman -Sy --needed --noconfirm git stow zsh curl make openssh
}

install_fedora() {
	log "Installing prerequisites (Fedora)..."
	sudo dnf install -y git stow zsh curl make openssh-clients
}

install_macos() {
	log "Ensuring Homebrew..."
	if ! have brew; then
		/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
	fi

	# shellenv for both Apple Silicon and Intel
	if [[ -x /opt/homebrew/bin/brew ]]; then
		eval "$(/opt/homebrew/bin/brew shellenv)"
	elif [[ -x /usr/local/bin/brew ]]; then
		eval "$(/usr/local/bin/brew shellenv)"
	fi

	log "Installing prerequisites (macOS via brew)..."
	brew update
	brew install git stow zsh curl gnu-make asdf
}

install_freebsd() {
	log "Installing prerequisites (FreeBSD)..."
	sudo pkg update -f
	# gmake is GNU make; stow is stow; git/curl/zsh are available
	sudo pkg install -y git stow zsh curl gmake
}

case "$PLATFORM" in
arch) install_arch ;;
fedora) install_fedora ;;
macos) install_macos ;;
freebsd) install_freebsd ;;
esac

# -------- Clone/update dotfiles --------
if [[ -d "$DOTFILES_DIR/.git" ]]; then
	log "Updating dotfiles in $DOTFILES_DIR..."
	git -C "$DOTFILES_DIR" pull --rebase || log "Warning: could not update dotfiles, continuing..."
else
	log "Cloning dotfiles to $DOTFILES_DIR..."
	git clone "$DOTFILES_REPO" "$DOTFILES_DIR"
fi

# -------- Build/apply dotfiles (make vs gmake) --------
MAKE_CMD="make"
if [[ "$PLATFORM" == "freebsd" ]]; then
	MAKE_CMD="gmake"
elif [[ "$PLATFORM" == "macos" ]]; then
	# prefer GNU make if available (brew installs as gmake)
	if have gmake; then MAKE_CMD="gmake"; fi
fi

log "Backing up existing files"
mkdir -p "$BACKUP_DIR"

(cd ~ && mv .zshrc "$BACKUP_DIR/")
(cd ~ && mv .bashrc "$BACKUP_DIR/")
(cd ~ && mv .config/gtk-3.0 "$BACKUP_DIR/")

log "Moving empty XDG user directories to .backup"
if [[ "$PLATFORM" != "macos" ]]; then
	for dir in Desktop Documents Downloads Music Pictures Public Templates Videos; do
		target="$HOME/$dir"
		if [[ -d "$target" ]]; then
			if [[ -z "$(ls -A "$target" 2>/dev/null)" ]]; then
				mv "$target" "$BACKUP_DIR/"
			fi
		fi
	done
fi
log "Link screenshots because Gnome sucks"
(mkdir ~/Pictures && ln -s ~/var/screenshots ~/Pictures/Screenshots)

log "Running $MAKE_CMD in dotfiles repo..."
(cd "$DOTFILES_DIR" && "$MAKE_CMD")

# -------- oh-my-zsh --------
if [[ -d "$OMZ_DIR" ]]; then
	log "oh-my-zsh already present at $OMZ_DIR"
else
	log "Cloning oh-my-zsh..."
	git clone --depth=1 https://github.com/ohmyzsh/ohmyzsh "$OMZ_DIR"
fi

# -------- Set zsh as default shell --------
log "Setting zsh as default shell..."
ZSH_PATH="$(command -v zsh)"
case "$PLATFORM" in
macos)
	sudo -u "$USER" chsh -s "$ZSH_PATH" || chsh -s "$ZSH_PATH"
	;;
*)
	sudo chsh -s "$ZSH_PATH" "$USER" || sudo usermod -s "$ZSH_PATH" "$USER" || chsh -s "$ZSH_PATH"
	;;
esac

log "Please open a new shell or terminal so your shell config reloads."

log "Done."
