#!/bin/bash

curl -Ls https://nodejs.org/dist | grep -ioP 'v\d+\.\d+\.\d+' | sort -rV | uniq | tee /tmp/versions.txt > /dev/null

versions=$(cat /tmp/versions.txt)

case $1 in
    help|h|-h|--help)
        echo "For alle existing versions, see /tmp/versions.txt"

        exit
    ;;
esac

for ver in $(cat /tmp/versions.txt); do
    [[ $1 != "$ver" ]] && continue
    ok=1
done

version=$1

if ! [[ $1 ]]; then
    version=$(curl -Ls https://nodejs.org/dist | grep -ioP 'v\d+\.\d+\.\d+' | sort -rV | uniq | head -n 1)
elif ! [[ $ok ]]; then
    echo "Wrong Version! For alle existing versions, see /tmp/versions.txt"
    exit 1
fi

switch() {
    for bin in $(ls /usr/local/node/$version/bin); do
        ln -fs /usr/local/node/$version/bin/$bin /usr/bin/$bin
    done
}

if [[ -d /usr/local/node/$version ]]; then
    echo "Version $version already installed! Switching..."
    sleep 1.5

    switch

    reset
    sleep 1

    echo "Switched to $version"
    sleep 1

    exit
fi

wget https://nodejs.org/dist/$version/node-$version-linux-x64.tar.xz || wget https://nodejs.org/dist/$version/node-$version.tar.gz
unxz node-$version-linux-x64.tar.xz || gunzip node-$version.tar
tar xvf node-$version-linux-x64.tar || tar xvf node-$version.tar
rm node-$version-linux-x64.tar || rm node-$version.tar

! [[ -d /usr/local/node ]] && mkdir /usr/local/node
mv node-$version-linux-x64 /usr/local/node/$version || mv node-$version /usr/local/node/$version
ln -fs /usr/local/node/$version/bin/* /usr/bin

[[ -n $(which corepack) ]] && corepack enable
curl -fsSL https://bun.sh/install | bash

switch

bun add -g npm-check-updates

reset

echo "Using $version"