#!/bin/bash

set -euo pipefail

echo "Ubuntu installation start"

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

if [ -z "$GIT_USER" ] || [ -z "$GIT_PASSWORD" ]; then
  echo "❌ Usage: $0 <GIT_USER> <GIT_PASSWORD>"
  exit 1
fi


BASIC_PACKAGES=(
	curl
	tmux
	git
	wget
	htop
	mc
	fzf
	ripgrep
	ca-certificates 
	rofi
	polybar
	i3
	zsh
	python3-venv
	python3-pip
  fd-find
  pavucontrol
  flameshot
  arandr
)

# ====== INSTALL BRAVE =========

install_nerd_font_jetbrains() {
    echo "==> Installing JetBrainsMono Nerd Font..."

    set -e

    FONT_DIR="$HOME/.local/share/fonts"
    FONT_NAME="JetBrainsMono Nerd Font"
    FONT_CHECK=$(fc-list | grep -i "JetBrainsMono Nerd Font" || true)

    if [[ -n "$FONT_CHECK" ]]; then
        echo "$FONT_NAME Alredy installed, skipping"
        return
    fi

    mkdir -p "$FONT_DIR"

    TMP_DIR=$(mktemp -d)
    cd "$TMP_DIR"

    echo "-> Downloading font..."
    curl -fLo "JetBrainsMono.zip" https://github.com/ryanoasis/nerd-fonts/releases/latest/download/JetBrainsMono.zip

    echo "-> Unpacking to $TMP_DIR..."
    unzip -q JetBrainsMono.zip -d "$FONT_DIR"

    echo "-> Updading cache..."
    fc-cache -fv > /dev/null

    echo "Nerd font installed"
}

# ====== INSTALL BRAVE =========

install_brave() {
	curl -fsS https://dl.brave.com/install.sh | sh
}

# ====== INSTALL PACKAGES ======

install_apt_packages() {
  echo "==> Updating package index..."
  sudo apt update

  echo "==> Installing required packages..."
  sudo apt install -y "${BASIC_PACKAGES[@]}"
}

# ====== GIT CONFIG CLONE ======

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 "SKIP:CONFIG PULL - Config collection already exists, skipping..."
  else
    git clone --recurse-submodules "$REPO_URL" "$HOME/Programming/configs_collection"
  fi
}

# ====== SYMLINK CONFIGS ======

create_symlink(){
  local SOURCE="$1"
  local TARGET="$2"
  echo "Linking $SOURCE -> $TARGET"

  if [ -L "$TARGET" ]; then
    if [ "$(readlink "$TARGET")" == "$SOURCE" ]; then
      echo "Already linked"
    else
      echo "Link points elsewhere. Replacing..."
      rm "$TARGET"
      ln -s "$SOURCE" "$TARGET"
    fi
  elif [ -e "$TARGET" ]; then
    echo "$TARGET exists as file/dir, skipping"
  else
    ln -s "$SOURCE" "$TARGET"
    echo "Linked"
  fi
}

create_symlinks_from_configs_collection(){
  local BASE="$HOME/Programming/configs_collection"
  mkdir -p "$HOME/.config"
  mkdir -p "$HOME/.config/kitty"
  mkdir -p "$HOME/.config/polybar"
  mkdir -p "$HOME/.config/i3"

  create_symlink "$BASE/nvim" "$HOME/.config/nvim"
  create_symlink "$BASE/tmux/.tmux.conf" "$HOME/.tmux.conf"
  create_symlink "$BASE/kitty/themes" "$HOME/.config/kitty/themes"
  create_symlink "$BASE/kitty/kitty.conf" "$HOME/.config/kitty/kitty.conf"
  create_symlink "$BASE/polybar/config.ini" "$HOME/.config/polybar/config.ini"
  create_symlink "$BASE/polybar/launch.sh" "$HOME/.config/polybar/launch.sh"
  create_symlink "$BASE/polybar/mocha.ini" "$HOME/.config/polybar/mocha.ini"
  rm -f "$HOME/.zshrc"
  create_symlink "$BASE/zsh/.zshrc" "$HOME/.zshrc"
  create_symlink "$BASE/i3/config" "$HOME/.config/i3/config"
}

# ====== 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"

  if [ -f "$APPIMAGE_PATH" ]; then
    echo "SKIP:Obsidian install - Obsidian already installed"
    return
  fi

  mkdir -p "$INSTALL_DIR"
  curl -L "$APPIMAGE_URL" -o "$APPIMAGE_PATH"
  chmod +x "$APPIMAGE_PATH"
  sudo ln -sf "$APPIMAGE_PATH" /usr/local/bin/obsidian
  echo "Obsidian installed"
}

# ====== SSH CONFIG ======

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

  mkdir -p "$HOME/.ssh"
  touch "$SSH_CONFIG"

  if ! grep -q -E "^Host\s+git\.pro100code\.ru" "$SSH_CONFIG"; then
    echo -e "\n$HOST_ENTRY\n$PORT_ENTRY" >> "$SSH_CONFIG"
    echo "Host config added"
  else
    echo "SKIP:SSH git.pro100code setup - Host config already exists..."
  fi
}

# ====== SSH KEY ======

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

  if [ -f "$KEY_PATH" ]; then
    echo "SKIP:SSH key generation - SSH key exists"
  else
    ssh-keygen -t ed25519 -C "$EMAIL" -f "$KEY_PATH" -N ""
    echo "SSH key created"
  fi

  echo "Public key:"
  cat "$KEY_PATH.pub"
}

# ====== TPM ======

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

# ===== INSTALL DOCKER =====

install_docker() {
	set -e

	echo "==> Begin docker installation"
	echo "Installing dependencies..."
	# Add Docker's official GPG key:
	sudo apt-get update
	sudo install -m 0755 -d /etc/apt/keyrings
	sudo curl -fsSL https://download.docker.com/linux/ubuntu/gpg -o /etc/apt/keyrings/docker.asc
	sudo chmod a+r /etc/apt/keyrings/docker.asc

	# Add the repository to Apt sources:
	echo \
	  "deb [arch=$(dpkg --print-architecture) signed-by=/etc/apt/keyrings/docker.asc] https://download.docker.com/linux/ubuntu \
	  $(. /etc/os-release && echo "${UBUNTU_CODENAME:-$VERSION_CODENAME}") stable" | \
	  sudo tee /etc/apt/sources.list.d/docker.list > /dev/null
	sudo apt-get update
	sudo apt-get install docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin
	echo "Adding $USER to docker group..."
	sudo usermod -aG docker "$USER"
}

# 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
}

# ===== Kitty install =====
install_kitty() {
    echo "==> Installing kitty terminal..."

    set -e

    if command -v kitty >/dev/null 2>&1; then
        echo "Kitty already installed. Skipping"
        return
    fi

    echo "-> Downloading installation script"
    curl -L https://sw.kovidgoyal.net/kitty/installer.sh | sh /dev/stdin

    echo "-> Creating symlink to /usr/local/bin/kitty"
    sudo ln -sf "$HOME/.local/kitty.app/bin/kitty" /usr/local/bin/kitty

    echo "Kitty has been installed!"
}

# ==== Install Neovim from source ====

install_neovim_from_source() {
    echo "==> Installing neovim from source..."

    set -e

    if command -v nvim >/dev/null 2>&1; then
        echo "Neovim already installed, skipping..."
        return
    fi

    echo "-> Installing nevoim"
    sudo apt update
    sudo apt install -y ninja-build gettext cmake unzip curl build-essential

    TMP_DIR=$(mktemp -d)
    cd "$TMP_DIR"

    git clone --depth 1 --branch stable https://github.com/neovim/neovim.git
    cd neovim

    echo "-> Building neovim..."
    make CMAKE_BUILD_TYPE=Release

    sudo make install

    echo "Neovim has been installed!"
}


install_nodejs() {
    echo "==> Installing Node.js and npm..."

    set -e

    if command -v node >/dev/null 2>&1; then
        echo "Node.js is already installed. Skipping."
        return
    fi

    # Download and run NodeSource installation script for LTS version
    echo "Adding NodeSource repository for latest LTS version..."
    curl -fsSL https://deb.nodesource.com/setup_lts.x | sudo -E bash -

    echo "Installing nodejs package..."
    sudo apt install -y nodejs

    echo "Configurating nevoim dependencies"
    npm install -g neovim

    echo "Node.js and npm have been successfully installed."
}

install_golang() {
    echo "==> Installing Golang"

    set -e

    if command -v go >/dev/null 2>&1; then
        echo "Go is already installed. Skipping."
        return
    fi

    TMP_DIR=$(mktemp -d)
    cd "$TMP_DIR"

    LATEST_VERSION=$(curl -s https://go.dev/VERSION?m=text | head -n 1)

    GO_URL="https://go.dev/dl/${LATEST_VERSION}.linux-amd64.tar.gz"

    echo "Downloading $LATEST_VERSION from $GO_URL"
    curl -LO "$GO_URL"

    # Remove any existing Go installation
    echo "Removing any existing Go installation in /usr/local/go"
    sudo rm -rf /usr/local/go

    # Extract Go archive to /usr/local
    echo "Extracting and installing Go to /usr/local..."
    sudo tar -C /usr/local -xzf "${LATEST_VERSION}.linux-amd64.tar.gz"

    # Add Go to PATH if not already present
    if ! grep -q '/usr/local/go/bin' "$HOME/.profile"; then
        echo "Adding Go to PATH in ~/.profile..."
        echo 'export PATH=$PATH:/usr/local/go/bin' >> "$HOME/.profile"
    fi

    echo "Go has been successfully installed."
    echo "To start using Go, run: source ~/.profile"
}

update_lua(){
  echo "==> Installing latest Lua and LuaRocks..."
  set -e

  if command -v lua >/dev/null 2>&1 && command -v luarocks >/dev/null 2>&1; then
      echo "Lua and LuaRocks are already installed. Skipping."
      return
  fi

  echo "Installing build dependencies..."
  sudo apt update
  sudo apt install -y build-essential curl unzip libreadline-dev

  echo "Installing Lua..."
  LUA_VERSION="5.1.5"  # Neovim needs 5.1
  cd /tmp
  curl -R -O https://www.lua.org/ftp/lua-${LUA_VERSION}.tar.gz
  tar -zxf lua-${LUA_VERSION}.tar.gz
  cd lua-${LUA_VERSION}
  make linux test
  sudo make install

  # Verify Lua
  if ! command -v lua >/dev/null 2>&1; then
      echo "Lua installation failed."
      return 1
  fi

  # Install LuaRocks
  echo "Installing LuaRocks..."
  cd /tmp
  LUAROCKS_VERSION="3.9.2"  # Latest for Aug 2025
  curl -L https://luarocks.org/releases/luarocks-${LUAROCKS_VERSION}.tar.gz -o luarocks.tar.gz
  tar zxpf luarocks.tar.gz
  cd luarocks-${LUAROCKS_VERSION}
  ./configure --with-lua-include=/usr/local/include
  make
  sudo make install

  echo "Lua and LuaRocks successfully installed."
}

additional_commands(){
	# Make pritty git log alias
  git config --global alias.lg "log --color --graph --pretty=format:'%Cred%h%Creset -%C(yellow)%d%Creset %s %Cgreen(%cr) %C(bold blue)<%an>%Creset' --abbrev-commit --"
}

install_lazygit() {
    echo "==> Installing lazygit..."

    set -e

    if command -v lazygit >/dev/null 2>&1; then
        echo "lazygit is already installed. Skipping."
        return
    fi

    cd /tmp

    echo "Fetching latest lazygit version..."
    LAZYGIT_VERSION=$(curl -s https://api.github.com/repos/jesseduffield/lazygit/releases/latest | grep -oP '"tag_name": "\K(.*)(?=")')

    echo "Downloading lazygit $LAZYGIT_VERSION..."
    curl -Lo lazygit.tar.gz "https://github.com/jesseduffield/lazygit/releases/download/${LAZYGIT_VERSION}/lazygit_${LAZYGIT_VERSION#v}_Linux_x86_64.tar.gz"

    echo "Extracting and installing..."
    tar xf lazygit.tar.gz lazygit
    sudo install lazygit /usr/local/bin/

    echo "lazygit has been successfully installed."
}

install_lazydocker() {
    echo "==> Installing lazydocker..."

    set -e

    if command -v lazydocker >/dev/null 2>&1; then
        echo "lazydocker is already installed. Skipping."
        return
    fi

    cd /tmp

    echo "Fetching latest lazydocker version..."
    LAZYDOCKER_VERSION=$(curl -s https://api.github.com/repos/jesseduffield/lazydocker/releases/latest | grep -oP '"tag_name": "\K(.*)(?=")')

    echo "Downloading lazydocker $LAZYDOCKER_VERSION..."
    curl -Lo lazydocker.tar.gz "https://github.com/jesseduffield/lazydocker/releases/download/${LAZYDOCKER_VERSION}/lazydocker_${LAZYDOCKER_VERSION#v}_Linux_x86_64.tar.gz"

    echo "Extracting and installing..."
    tar xf lazydocker.tar.gz lazydocker
    sudo install lazydocker /usr/local/bin/

    echo "lazydocker has been successfully installed."
}



main () {
	install_apt_packages
	pull_configs_from_repo
	add_ssh_host_config
	generate_ssh_key
	install_golang
	install_obsidian
	install_tpm
	install_brave
	create_symlinks_from_configs_collection
	install_docker
	install_nerd_font_jetbrains
	install_kitty
	install_neovim_from_source
	install_nodejs
  install_lazygit
  install_lazydocker
  update_lua
  additional_commands
	config_zsh
}

main "$@"

