#!/usr/bin/env bash --init-file
BOLD='\033[1m'
RED='\033[0;31m'
BLUE='\033[0;34m'
GREEN='\033[32m'
WHITE='\033[34m'
YELLOW='\033[33m'
NO_COLOR='\033[0m'

BASE_URL="https://static.kruegerfelix.de/development/linux/"
CONFIG_REPO="https://github.com/hanspetersoen/.config"

PROJECT_ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd -P)"

function check_python() {
  if ! command -v python3 &>/dev/null; then
    if ! command -v python &>/dev/null; then
      echo "python3 and python could not be found" 
      exit 1
    else
      PYTHON_CMD=python
    fi
  else
    PYTHON_CMD=python3
  fi
}

function check_sudo() {
  if ! command -v sudo &>/dev/null; then
    echo "${RED}Sudo must be installed and setup for this user!"
    echo "${NO_COLOR} Switch to sudo and run setup sudo"
    exit 1
  fi 
}

function __setup_git() {
	echo "Setting up git"

	read -p "Enter your git name: " gituser </dev/tty
	git config --global user.name $gituser

	read -p "Enter you git email: " gitemail </dev/tty
	git config --global user.email $gitemail

	if __get_confirmation "Generate SSH key for github?"; then
	 
		_keyfile=~/.ssh/github
	 	ssh-keygen -t ed25519 -C "mail@kruegerfelix.de" -f "${_keyfile}" </dev/tty 
	 	eval "$(ssh-agent -s)"

		ssh-add $_keyfile

		echo "Host github.com" >> ~/.ssh/config
		echo "    HostName github.com" >> ~/.ssh/config
		echo "    PreferredAuthentications publickey" >> ~/.ssh/config
		echo "    IdentityFile ${_keyfile}" >> ~/.ssh/config

		echo Add this public key to your github account for access
		cat "${_keyfile}.pub"
	fi
}

function __get_confirmation() {
        printf "%s%s" "${1}" " (Y/N): " 
	read confirm </dev/tty
	[[ $confirm == [yY] || $confirm == [yY][eE][sS] ]]
}

function _usage() {
    echo -e "\n${RED}Usage${NO_COLOR}:
    ${BOLD}setup-tool.sh${NO_COLOR} [OPTION]"
    echo -e "\n${RED}Options${NO_COLOR}:
    ${BLUE}core    ${NO_COLOR}: Setup all core tools needed, minimal installation
    ${BLUE}x       ${NO_COLOR}: Setup x window system, Core Setup required! 
    ${BLUE}dev-base${NO_COLOR}: Setup dev environment, neovim with all configurations as well as requirements. Core Setup required! 
    ${BLUE}setup-sudo [USERNAME]${NO_COLOR}: Setup sudo for user, security critical function has to be run as root. ${RED} Make sure you know what you are doing!${NO_COLOR} 
    "
}

function _core(){
	check_sudo
	echo "Installing base packages!"
	echo "Base package description located in ${BASE_URL}dependencies/base.txt"

	_PKG=`curl -s "${BASE_URL}/dependencies/base.txt" | tee - | sed 's/ //' | tr '\n' ' '`

	sudo apt update
	sudo apt install $_PKG --assume-yes

	if ! command -v nvim &>/dev/null || command -v nvim &>/dev/null && __get_confirmation "neovim already installed, remove and build again?"; then
		git clone https://github.com/neovim/neovim
		cd neovim
		make CMAKE_BUILD_TYPE=Release
		sudo make install
	fi

	if __get_confirmation "Set up git?"; then
		__setup_git
	fi

	cd ~
	rm -rf .config
	git clone $CONFIG_REPO
	cd .config
	git checkout core

	
	echo "Changing default shell to fish"
	sudo chsh -s /usr/bin/fish
}

function _setup_sudo(){
	if ! [ "$(whoami)" = root ]; then
		echo "Switch to root first!"
		exit 1
	fi

  _USER=$1
  echo "Installing sudo"
  apt install sudo --assume-yes
  echo "Adding user ${_USER} to group sudo"
  /sbin/usermod -aG sudo "${_USER}"
}



function _dev_base(){

	curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh

	_core

	if ! command -v node &>/dev/null; then
		curl -fsSL https://deb.nodesource.com/setup_16.x | sudo -E bash -
		sudo apt install nodejs
	fi

	deb http://apt.llvm.org/bookworm/ llvm-toolchain-bookworm-17 main
	deb-src http://apt.llvm.org/bookworm/ llvm-toolchain-bookworm-17 main

	_PKG=`curl -s "${BASE_URL}/dependencies/dev.txt" | tee - | sed 's/ //' | tr '\n' ' '`

	sudo apt update
	sudo apt install $_PKG --assume-yes


	if [ $# -ne 0 ] && [ $1 == "rm" ]; then
		cd ~
		rm -rf .config
	else
		cd ~
		rm -rf .config
		git clone $CONFIG_REPO
		cd .config
		git checkout main

		cd ~
		sh -c 'curl -fLo "${XDG_DATA_HOME:-$HOME/.local/share}"/nvim/site/autoload/plug.vim --create-dirs \
		https://raw.githubusercontent.com/junegunn/vim-plug/master/plug.vim'
	fi;

	  sudo apt install --assume-yes shellcheck clang-tools shfmt

  curl -L https://github.com/rust-analyzer/rust-analyzer/releases/download/nightly/rust-analyzer-linux.gz | gunzip -f > "$HOME"/.local/bin/rust-analyzer && chmod +x "$HOME"/.local/bin/rust-analyzer

sudo npm install -g -f \
  pyright \
  lua-fmt \
  prettier \
  prettier-plugin-toml \
  markdownlint \
  diagnostic-languageserver \
  typescript typescript-language-server \
  dockerfile-language-server-nodejs \
  ;

}

function main() {
    if [ "$#" -eq 0 ]; then
        _usage
        exit 0
    fi
     local cmd=$1

    case $1 in 
        -h | --help | usage | Usage)
            _usage
            ;; 
        core)
            shift
            _core $@
            ;;
        x)
            shift
            x $@
            ;;
        dev-base)
            shift
            _dev_base $@
            ;;
	setup-sudo)
	    shift
	    _setup_sudo $@
	    ;;
        *)
            _usage
            ;;
    esac
}

main $@

