#!/bin/bash

set -euo pipefail

echo "Arch linux installation start"

GIT_USER="{$1:-}"
GIT_PASSWORD="{$2:-}"

# Check if git user and password installed
if [ -z "$GIT_USER" ] || [ -z "$GIT_PASSWORD" ]; then
  echo "Git user and password must be installed to use this script"
  exit 1
fi

# Packages list to install
BASIC_PACKAGES=(
	vim
	git
	curl
	wget
	htop
	tmux
	zsh
	timeshift
	fuse2
	polybar
	rofi
	neovim
	nodejs-lts-iron
  npm
  ttf-jetbrains-mono-nerd
  mc
  kitty
  telegram-desktop
  fzf
  xorg-xrandr
  lazygit
  docker
  docker-compose
  lsof
)

YAY_PACKAGES=(
	brave-bin
)

# Install yay if needed
install_yay_if_needed() {
	if ! command -v yay &> /dev/null; then
		echo "yay not found. Installing..."
		sudo pacman -S --needed --noconfirm base-devel git
		git clone https://aur.archlinux.org/yay.git /tmp/yay
		(cd /tmp/yay && makepkg -si --noconfirm)
	fi
}

# Install yay packages
install_yay_packages() {
	for pkg in "${YAY_PACKAGES[@]}"; do
		if ! pacman -Q "$pkg" &> /dev/null; then
			echo "Installing $pkg"
			yay -S --noconfirm "$pkg"
		else
			echo "$pkg already installed via yay, skipping"
		fi
	done
}

# Install pacman packages
install_pacman_packages() {
	sudo pacman -Sy --noconfirm
	for pkg in "${BASIC_PACKAGES[@]}"; do
		if ! pacman -Q "$pkg" &> /dev/null; then
			echo "Installing $pkg"
			sudo pacman -S --noconfirm "$pkg"
		else
			echo "$pkg already installed, skipping"
		fi
	done
}

# Install zomro ssh ports
add_ssh_host_config() {
	local SSH_CONFIG="$HOME/.ssh/config"
	local HOST_ENTRY="Host git.pro100code.ru"
	local PORT_ENTRY="  Port 2244"

	# Make directory and file if not existing
	mkdir -p "$HOME/.ssh"
	touch "$SSH_CONFIG"

	# Check if host already exists
	if ! grep -q -E "^Host\s+git\.pro100code\.ru" "$SSH_CONFIG"; then
		echo -e "\n$HOST_ENTRY\n$PORT_ENTRY" >> "$SSH_CONFIG"
		echo "Host installed to ~/.ssh/config:"
		echo "$HOST_ENTRY"
		echo "$PORT_ENTRY"
	else
		echo "Host git.pro100code.ru already installed in ~/.ssh/config"
	fi
}

# Pulling configs collection from my repo
pull_configs_from_repo(){
	local REPO_URL="https://${GIT_USER}:${GIT_PASSWORD}@git.pro100code.ru/t0xa/configs_collection.git"
	mkdir -p "$HOME/Programming"
	if [ -d "$HOME/Programming/configs_collection" ]; then
		echo "Config collection directory already exists, skipping..."
	else
		git clone --recurse-submodules "$REPO_URL" "$HOME/Programming/configs_collection"
	fi
}

# Universal symlink creator
create_symlink(){
	local SOURCE="$1"
	local TARGET="$2"
	echo "Trying to create symlink $SOURCE -- $TARGET..."

	if [ -L "$TARGET" ]; then
		# If symlink already created
		if [ "$(readlink "$TARGET")" == "$SOURCE" ]; then
			echo "Symlink $SOURCE -- $TARGET already created"
		else
			echo "Symlink $TARGET pointing to invalid target. Correcting..."
			rm "$TARGET"
			ln -s "$SOURCE" "$TARGET"
			echo "Symlink updates: $SOURCE -- $TARGET"
		fi
	elif [ -e "$TARGET" ]; then
	 	echo "Target $TARGET already exists as file or directory, skipping."
	else
		ln -s "$SOURCE" "$TARGET"
		echo "Created symlink: $SOURCE -- $TARGET"
	fi
}

# Create symlinks for necessary configs
create_symlinks_from_configs_collection(){
	mkdir -p "$HOME/.config"
  # Create symlink for nvim directory
  if [ -e "$HOME/.config/nvim" ]; then
	 	echo "Neovim config directory already exists as file or directory, skipping."
  else
    create_symlink "$HOME/Programming/configs_collection/nvim" "$HOME/.config"
  fi
  # Create tmux config symlink
  create_symlink "$HOME/Programming/configs_collection/tmux/.tmux.conf" "$HOME/.tmux.conf"
  # Create symlinks for kitty
  mkdir -p "$HOME/.config/kitty"
  create_symlink "$HOME/Programming/configs_collection/kitty/themes" "$HOME/.config/kitty/themes"
  create_symlink "$HOME/Programming/configs_collection/kitty/kitty.conf" "$HOME/.config/kitty/kitty.conf"
  # Create symlinks for polybar
  mkdir -p "$HOME/.config/polybar"
  create_symlink "$HOME/Programming/configs_collection/polybar/config.ini" "$HOME/.config/polybar/config.ini"
  create_symlink "$HOME/Programming/configs_collection/polybar/launch.sh" "$HOME/.config/polybar/launch.sh"
  create_symlink "$HOME/Programming/configs_collection/polybar/mocha.ini" "$HOME/.config/polybar/mocha.ini"
  # Create symlinks for zsh
  rm "$HOME/.zshrc"
  create_symlink "$HOME/Programming/configs_collection/zsh/.zshrc" "$HOME/.zshrc"
  # Create symlinks for i3
  mkdir -p "$HOME/.config/i3"
  create_symlink "$HOME/Programming/configs_collection/i3/config" "$HOME/.config/i3/config"
}

# Generate SSH key
generate_ssh_key() {
	local EMAIL="pro100ton@gmail.com"
	local KEY_PATH="$HOME/.ssh/id_ed25519"

	# Check if key exists
	if [ -f "$KEY_PATH" ]; then
		echo "SSH-key already exists: $KEY_PATH"
	else
		echo "Generating new SSH key..."
		ssh-keygen -t ed25519 -C "$EMAIL" -f "$KEY_PATH" -N ""
		echo "SSH key created"
	fi
	echo "Key to copy:"
	echo "----------------------------------------------"
	cat "$KEY_PATH.pub"
	echo "----------------------------------------------"
}

# Install obsidian
install_obsidian() {
	local INSTALL_DIR="$HOME/Applications"
	local APPIMAGE_URL="https://github.com/obsidianmd/obsidian-releases/releases/download/v1.8.10/Obsidian-1.8.10.AppImage"
	local APPIMAGE_PATH="$INSTALL_DIR/Obsidian.AppImage"

	# Check if already installed
	if [ -f "$APPIMAGE_PATH" ]; then
		echo "Obsidian already installed inside $APPIMAGE_PATH"
		return
	fi

	echo "Installing Obsidian..."
	echo "Trying to download AppImage..."

	# Creating directory if needed
	mkdir -p "$HOME/Applications"

	sudo curl -L "$APPIMAGE_URL" -o "$APPIMAGE_PATH"
	sudo chmod +x "$APPIMAGE_PATH"

	# Create symling to /usr/local/bin
	sudo ln -sf "$APPIMAGE_PATH" /usr/local/bin/obsidian

	echo "Obsidian has been installed!"
}

# Install tmux plugin manager
install_tpm() {
  local TPM_DIR="$HOME/.tmux/plugins/tpm"
  if [ -d "$TPM_DIR" ]; then
    echo "TPM already installed. skipping..."
  else
    echo "Begin TPM installation..."
    git clone https://github.com/tmux-plugins/tpm "$TPM_DIR"
    echo "TPM installed!"
  fi
}

# Config ZSH
config_zsh() {
  # Install P10K
  local ZSH_CUSTOM="$HOME/.oh-my-zsh/custom"
  local P10K_DIR="$ZSH_CUSTOM/themes/powerlevel10k"

  echo "Installing Oh my ZSH..."
  # rm -rf "$HOME/.oh-my-zsh"
  # RUNZSH=no CHSH=no KEEP_ZSHRC=yes sh -c "$(curl -fsSL https://raw.githubusercontent.com/ohmyzsh/ohmyzsh/master/tools/install.sh)"
  #

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

  # Installing plugins
  # zsh-autosuggestions
  if [ ! -d "$ZSH_CUSTOM/plugins/zsh-autosuggestions" ]; then
    git clone https://github.com/zsh-users/zsh-autosuggestions "$ZSH_CUSTOM/plugins/zsh-autosuggestions"
  fi

  # zsh-fzf-history-search
  if [ ! -d "$ZSH_CUSTOM/plugins/zsh-fzf-history-search" ]; then
    git clone https://github.com/joshskidmore/zsh-fzf-history-search "$ZSH_CUSTOM/plugins/zsh-fzf-history-search"
  fi

  # powerlevel10k
  if [ ! -d "$ZSH_CUSTOM/themes/powerlevel10k" ]; then
    git clone --depth=1 https://github.com/romkatv/powerlevel10k.git "$ZSH_CUSTOM/themes/powerlevel10k"
  fi
  
  # Make ZSH default shell
  # if [ "$SHELL" != "/bin/zsh" ]; then
  #   echo "Changing shell to ZSH..."
  #   sudo chsh -s /bin/zsh $USER
  # fi
  local CURRENT_SHELL="$(which zsh)"
  if [ "$SHELL" != "$CURRENT_SHELL" ]; then
    echo "Changing shell to ZSH..."
    sudo chsh -s "$CURRENT_SHELL" "$USER"
    echo "!!! REMEMBER TO LOG OUT AND LOG IN AFTER SHELL CHANGE !!!"
  fi
}

# Docker data location settings
config_docker_data_location() {
  local NEW_DOCKER_ROOT="/home/$USER/Programming/Docker"
  local DAEMON_CONFIG="/etc/docker/daemon.json"

  echo "Starting setting up dokcer environment..."
  sudo mkdir -p "$NEW_DOCKER_ROOT"
  sudo chown root:root "$NEW_DOCKER_ROOT"
  sudo chmod 711 "$NEW_DOCKER_ROOT"

  sudo mkdir -p /etc/docker
  echo "{
    \"data-root\": \"$NEW_DOCKER_ROOT\"
  }" | sudo tee "$DAEMON_CONFIG" > /dev/null
  
  sudo systemctl daemon-reexec
  sudo systemctl daemon-reload
  sudo systemctl restart docker

  echo "Docker env configured!"
  echo "Adding user to docker group..."
  sudo groupadd -f docker
  sudo usermod -aG docker "$USER"
  echo "User has been added to docker group!"
}


main () {
	install_yay_if_needed
	install_pacman_packages
	install_yay_packages
	add_ssh_host_config
	pull_configs_from_repo
	install_obsidian
	generate_ssh_key
  install_tpm
	create_symlinks_from_configs_collection
  config_docker_data_location
  config_zsh
}

main "$@"
