#!/bin/bash
set -e
sudo -v

if [ -f /etc/os-release ]; then
    . /etc/os-release
    VER=$VERSION_ID
else
    VER="0"
fi

if [ "$(dpkg -l | awk '/ubuntu-desktop/ {print }' | wc -l)" -ge 1 ]; then
    DESKTOP="yes"
else
    DESKTOP="no"
fi

if [[ "$(systemd-detect-virt)" == *"wsl"* ]]; then
    WSL="yes"
else
    WSL="no"
fi

echo -e ' \e[H\e[2J
 \e[0;31m                .-.\e[0;37m
 \e[0;31m          .-"``(|||)\e[0;37m
 \e[0;31m       ,`\ \    `-`.\e[0;37m               88                         88
 \e[0;31m      /   \ "``-.   `\e[0;37m              88                         88
 \e[0;31m    .-.  ,       `___:\e[0;37m    88   88  88,888,  88   88  ,88888, 88888  88   88
 \e[0;31m   (:::) :        ___ \e[0;37m    88   88  88   88  88   88  88   88  88    88   88
 \e[0;31m    `-`  `       ,   :\e[0;37m    88   88  88   88  88   88  88   88  88    88   88
 \e[0;31m      \   / ,..-`   ,\e[0;37m     88   88  88   88  88   88  88   88  88    88   88
 \e[0;31m       `./ /    .-.`\e[0;37m      "88888"  "88888"  "88888"  88   88  "8888 "88888"
 \e[0;31m         `-..-(   )\e[0;37m
 \e[0;31m               `-`\e[0;37m


    \e[1;32mCMtec Ubuntu install/Update script\e[0;37m
    \e[0;35mUbuntu version = '$VER'\e[0;37m
    \e[0;35mDesktop = '$DESKTOP'\e[0;37m
    \e[0;35mWSL = '$WSL'\e[0;37m
'

# *** System applications ***
printf -- '\033[32m *** System applications ***\n\033[37m'

# Ubuntu 20.04 workaround
if [ "$WSL" == "yes" ]; then
    sudo apt -y purge --auto-remove neovim
fi

# Update system
printf -- '\033[33m Updating system\n\033[37m'
sudo apt update
sudo apt upgrade -y
if [ "$WSL" == "no" ]; then
    if dpkg -s flatpak &>/dev/null; then
        flatpak update -y
    else
        sudo add-apt-repository -y ppa:flatpak/stable
        sudo apt update
        sudo apt install -y flatpak
        flatpak remote-add --if-not-exists flathub https://flathub.org/repo/flathub.flatpakrepo
        flatpak install -y flathub com.github.tchx84.Flatseal
    fi
fi
if dpkg -s snap &>/dev/null; then
    sudo snap refresh
else
    sudo apt install -y snap
fi

# Install system packages
printf -- '\033[33m Installing system packages\n\033[37m'
mkdir -p ~/.local/bin
sudo apt install -y gawk imagemagick gpg ninja-build gettext cmake unzip curl build-essential libssl-dev libffi-dev file libudev-dev pkg-config locales btop ncdu ranger timeshift
ln -sf ~/linuxbox/bashrc_ubuntu ~/.bashrc
if [ "$WSL" == "yes" ]; then
    ln -sf ~/linuxbox/gitconfig.work ~/.gitconfig
else
    ln -sf ~/linuxbox/gitconfig ~/.gitconfig
    mkdir -p ~/.config/alacritty
    ln -sf ~/linuxbox/config/alacritty/alacritty.toml ~/.config/alacritty/alacritty.toml
fi
ln -sf ~/linuxbox/update_wrapper.sh ~/.local/bin/update
ln -sf ~/linuxbox/start_nvim.sh ~/.local/bin/start_nvim
ln -sf ~/linuxbox/start_toolbox.sh ~/.local/bin/start_toolbox

# Install brew
printf -- '\033[33m Installing Homebrew\n\033[37m'
sudo apt-get install -y -qq build-essential curl file git

export NONINTERACTIVE=1
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
BREW_PREFIX="/home/linuxbrew/.linuxbrew"
if [ -d "$BREW_PREFIX" ]; then
    eval "$("$BREW_PREFIX"/bin/brew shellenv)"
else
    echo "[!] Homebrew install failed or brew not found at expected location."
    exit 1
fi
brew --version >/dev/null && echo "[✓] Homebrew installed successfully."

# Setup locals
printf -- '\033[33m Setup locals\n\033[37m'
sudo locale-gen "en_US.UTF-8"
sudo update-locale LANG=en_US.UTF-8

# Install rust
printf -- '\033[33m Installing Rust\n\033[37m'
cd ~
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- --no-modify-path -y
if [ "$WSL" == "yes" ]; then
    source "$HOME/.cargo/env"
fi
rustup self update
rustup update stable
rustup default stable

# Install python
printf -- '\033[33m Installing python\n\033[37m'
sudo apt install -y python3 python3-pip python3-venv python3-dev pipx
if [ "$VER" == "22.04" ]; then
    pip3 install pynvim
else
    sudo apt install -y python3-pynvim
fi

# Install node
printf -- '\033[33m Installing node\n\033[37m'
cd ~
curl -sL https://deb.nodesource.com/setup_18.x | sudo -E bash -
sudo apt install -y nodejs
npm config set prefix "${HOME}/.npm"

# Install fzf
printf -- '\033[33m Installing fzf\n\033[37m'
if [ -d ~/.fzf ]; then rm -rf ~/.fzf; fi
git clone --depth 1 https://github.com/junegunn/fzf.git ~/.fzf
~/.fzf/install --all

# Install tmux
printf -- '\033[33m Installing tmux\n\033[37m'
sudo apt install -y libevent-dev ncurses-dev build-essential bison pkg-config
cd ~
wget https://github.com/tmux/tmux/releases/download/3.3a/tmux-3.3a.tar.gz
tar xzvf tmux-3.3a.tar.gz
cd tmux-3.3a
./configure
make && sudo make install
ln -sf ~/linuxbox/tmux.conf ~/.tmux.conf

# Install VirtualHere client
printf -- '\033[33m Installing VirtualHere client\n\033[37m'
cd ~
wget https://www.virtualhere.com/sites/default/files/usbclient/scripts/virtualhereclient.service
wget https://www.virtualhere.com/sites/default/files/usbclient/vhclientx86_64
wget https://www.virtualhere.com/sites/default/files/usbclient/vhuit64
chmod +x ./vhclientx86_64
chmod +x ./vhuit64
sudo mv ./vhclientx86_64 /usr/sbin
sudo mv ./vhuit64 /usr/sbin
echo "$USER ALL=(ALL:ALL) NOPASSWD: /usr/sbin/vhclientx86_64" | sudo tee /etc/sudoers.d/$USER+vhclientx86_64
echo "$USER ALL=(ALL:ALL) NOPASSWD: /usr/sbin/vhuit64" | sudo tee /etc/sudoers.d/$USER+vhuit64
sudo mv virtualhereclient.service /etc/systemd/system/virtualhereclient.service
# sudo systemctl daemon-reload
# sudo systemctl enable virtualhereclient.service
# sudo systemctl start virtualhereclient.service

# Install teensy udev rules (only for non docker system)
if [ ! -f /.dockerenv ]; then
    printf -- '\033[33m Installing teensy udev rules\n\033[37m'
    sudo rm -f /tmp/00-teensy.rules /etc/udev/rules.d/00-teensy.rules /lib/udev/rules.d/00-teensy.rules
    sudo wget -O /tmp/00-teensy.rules https://www.pjrc.com/teensy/00-teensy.rules
    sudo install -o root -g root -m 0664 /tmp/00-teensy.rules /lib/udev/rules.d/00-teensy.rules
    sudo service udev restart
    sudo udevadm control --reload-rules
    sudo udevadm trigger
fi

# Install neovim
printf -- '\033[33m Installing neovim\n\033[37m'
sudo apt install -y bat fd-find
cd ~
if [ -d ~/neovim ]; then rm -rf ~/neovim; fi
git clone https://github.com/neovim/neovim
cd neovim && git checkout stable
make CMAKE_BUILD_TYPE=RelWithDebInfo
cd build && cpack -G DEB && sudo dpkg -i nvim*.deb
if [ -d ~/neovim ]; then rm -rf ~/neovim; fi
mkdir -p ~/.config/nvim
ln -sf ~/linuxbox/config/nvim/init.lua ~/.config/nvim/init.lua

# Install caffeine
if [ "$WSL" == "no" ]; then
    printf -- '\033[33m Installing caffeine\n\033[37m'
    sudo apt install -y caffeine
fi

# Install lazygit
printf -- '\033[33m Installing lazygit\n\033[37m'
cd ~
LAZYGIT_VERSION=$(curl -s "https://api.github.com/repos/jesseduffield/lazygit/releases/latest" | grep -Po '"tag_name": "v\K[^"]*')
curl -Lo lazygit.tar.gz "https://github.com/jesseduffield/lazygit/releases/latest/download/lazygit_${LAZYGIT_VERSION}_Linux_x86_64.tar.gz"
tar xf lazygit.tar.gz lazygit
sudo install lazygit /usr/local/bin
rm ~/lazygit && rm ~/lazygit.tar.gz
mkdir -p ~/.config/lazygit
ln -sf ~/linuxbox/config/lazygit/config.yml ~/.config/lazygit/config.yml

# Install gdu
printf -- '\033[33m Installing gdu\n\033[37m'
if [ $VER = "22.04" ]; then
    sudo add-apt-repository -y ppa:daniel-milde/gdu
fi
sudo apt update
sudo apt install -y gdu

# Install ruby
printf -- '\033[33m Installing ruby\n\033[37m'
sudo apt install -y ruby ruby-dev
sudo gem install neovim

# Install bottom
printf -- '\033[33m Installing bottom\n\033[37m'
cd ~
curl -LO https://github.com/ClementTsang/bottom/releases/download/0.9.1/bottom_0.9.1_amd64.deb
sudo dpkg -i bottom_0.9.1_amd64.deb
rm ~/bottom_0.9.1_amd64.deb

# Install go
printf -- '\033[33m Installing go\n\033[37m'
sudo apt install -y golang

# Install php
printf -- '\033[33m Installing php\n\033[37m'
sudo apt install -y php php-curl php-xml php-mbstring

# Install luarocks
printf -- '\033[33m Installing luarocks\n\033[37m'
sudo apt install -y luarocks

# Install composer
printf -- '\033[33m Installing composer\n\033[37m'
sudo apt install -y composer

# Install java
printf -- '\033[33m Installing java\n\033[37m'
if [ "$WSL" == "yes" ]; then
    sudo add-apt-repository -y ppa:linuxuprising/java
    sudo apt update
    sudo apt install -y oracle-java17-installer
else
    sudo apt install -y default-jdk
fi

# Install julia
printf -- '\033[33m Installing julia\n\033[37m'
wget https://julialang-s3.julialang.org/bin/linux/x64/1.9/julia-1.9.0-linux-x86_64.tar.gz
tar -xvzf julia-1.9.0-linux-x86_64.tar.gz
sudo cp -r julia-1.9.0 /opt/
sudo ln -sf /opt/julia-1.9.0/bin/julia /usr/local/bin/julia
rm julia-1.9.0-linux-x86_64.tar.gz*
rm -rf julia-1.9.0

# Install ble.sh
printf -- '\033[33m Installing ble.sh\n\033[37m'
if [ -d ~/ble.sh ]; then rm -rf ~/ble.sh; fi
cd ~
git clone --recursive --depth 1 --shallow-submodules https://github.com/akinomyoga/ble.sh.git
make -C ble.sh install PREFIX=~/.local
if [ -d ~/ble.sh ]; then rm -rf ~/ble.sh; fi
ln -sf ~/linuxbox/blerc ~/.blerc

# Install platformio
printf -- '\033[33m Installing platformio\n\033[37m'
if [ "$VER" == "24.04" ]; then
    pipx install platformio
    pipx ensurepath
else
    pip3 install platformio
fi

# Install neovim for node
printf -- '\033[33m Installing neovim for node\n\033[37m'
sudo npm install -g neovim

# Install rust embedded stuff
printf -- '\033[33m Installing Rust embedded stuff\n\033[37m'
cd ~
rustup target add thumbv6m-none-eabi
cargo install elf2uf2-rs --locked
cargo install probe-run
mkdir -p ~/.local/bin
ln -sf ~/linuxbox/pico-load.sh ~/.local/bin/pico-load

# Install tree sitter cli
printf -- '\033[33m Installing tree sitter cli\n\033[37m'
cd ~
cargo install tree-sitter-cli

# Install ripgrep
printf -- '\033[33m Installing ripgrep\n\033[37m'
cargo install ripgrep

# Install eza
printf -- '\033[33m Installing eza\n\033[37m'
cargo install eza

# Install zoxide
printf -- '\033[33m Installing zoxide\n\033[37m'
cargo install zoxide --locked

# Install starship
printf -- '\033[33m Installing starship\n\033[37m'
cargo install starship --locked
ln -sf ~/linuxbox/config/starship.toml ~/.config/starship.toml

printf -- '\033[33m Installing LSP servers\n\033[37m'
# Install LSP servers
printf -- '\033[33m Installing LSP servers\n\033[37m'
rustup component add rust-analyzer clippy rustfmt
sudo npm i -g bash-language-server pyright
sudo npm install --save-dev prettier
sudo apt install -y shfmt clangd clang-format
pipx install black
pipx install isort
pipx install mdformat
brew install lua-language-server marksman
cargo install stylua
ln -sf ~/linuxbox/luacheckrc ~/.luacheckrc

# *** Desktop applications ***
if [ "$WSL" == "no" ]; then
    printf -- '\033[32m *** Desktop applications ***\n\033[37m'

    if [ "$DESKTOP" == "yes" ]; then
        printf -- '\033[33m Installing Krita\n\033[37m'
        flatpak install -y flathub org.kde.krita

        printf -- '\033[33m Installing KiCad\n\033[37m'
        flatpak install -y flathub org.kicad.KiCad

        printf -- '\033[33m Installing FreeCad\n\033[37m'
        flatpak install -y flathub org.freecadweb.FreeCAD

        printf -- '\033[33m Installing Moonlight\n\033[37m'
        flatpak install -y flathub com.moonlight_stream.Moonlight

        printf -- '\033[33m Installing DrawIo\n\033[37m'
        flatpak install -y flathub com.jgraph.drawio.desktop

        # Install VSCode
        printf -- '\033[33m Installing VSCode\n\033[37m'
        sudo snap install --classic code

        # Install gnome-shell-extension-manager
        printf -- '\033[33m Installing gnome-shell-extension-manager\n\033[37m'
        sudo apt install -y gnome-shell-extension-manager

        # Install gnome tweaks
        printf -- '\033[33m Installing gnome tweaks\n\033[37m'
        sudo apt install -y gnome-tweaks

        # Install remmina
        printf -- '\033[33m Installing remmina\n\033[37m'
        sudo apt install -y remmina

        # Install feh
        printf -- '\033[33m Installing feh\n\033[37m'
        sudo apt install -y feh

        # Install NerdFonts
        printf -- '\033[33m Installing NerdFonts\n\033[37m'
        mkdir -p /home/$USER/.local/share/fonts
        cd /home/$USER/.local/share/fonts
        wget https://github.com/ryanoasis/nerd-fonts/releases/download/v3.2.1/CodeNewRoman.zip
        unzip -o CodeNewRoman.zip
        rm CodeNewRoman.zip
        wget https://github.com/ryanoasis/nerd-fonts/releases/download/v3.2.1/NerdFontsSymbolsOnly.zip
        unzip -o NerdFontsSymbolsOnly.zip
        rm NerdFontsSymbolsOnly.zip
        fc-cache -fv

        # Install Alacritty
        printf -- '\033[33m Installing Alacritty\n\033[37m'
        sudo add-apt-repository ppa:aslatter/ppa
        sudo apt update
        sudo apt install -y alacritty

        # Install Brave Browser
        printf -- '\033[33m Installing Brave Browser\n\033[37m'
        sudo curl -fsSLo /usr/share/keyrings/brave-browser-archive-keyring.gpg https://brave-browser-apt-release.s3.brave.com/brave-browser-archive-keyring.gpg
        echo "deb [signed-by=/usr/share/keyrings/brave-browser-archive-keyring.gpg] https://brave-browser-apt-release.s3.brave.com/ stable main" | sudo tee /etc/apt/sources.list.d/brave-browser-release.list
        sudo apt update
        sudo apt install -y brave-browser

        printf -- '\033[33m Installing Audio control\n\033[37m'
        if [ $VER == "22.04" ]; then
            # Install helvum
            sudo apt install -y pavucontrol
        fi
        if [ $VER == "24.04" ]; then
            # Install helvum
            sudo apt install -y pavucontrol helvum
        fi

    fi
fi

printf -- '\033[32m \n\n***** Update complete! Please restart your terminal. *****\n\n\033[37m'
