#!/bin/bash

# Usage:
# bash <(curl -s https://scripts.justman10000.de/installers/vscode.sh)

if [[ $1 == "-ri" ]]; then
    systemctl stop vscode.service

    mv /usr/local/vscode/user /tmp
    mv /usr/local/vscode/exts /tmp

    rm -r /usr/local/vscode
fi

version=$(curl -s https://api.github.com/repos/coder/code-server/releases | jq -r .[].name | head -n 1 | sed 's/v//g')
wget https://github.com/coder/code-server/releases/download/v$version/code-server-$version-linux-amd64.tar.gz
gunzip code-server-$version-linux-amd64.tar.gz
tar xvf code-server-$version-linux-amd64.tar
rm -r code-server-$version-linux-amd64.tar
mv code-server-$version-linux-amd64 /usr/local/vscode
ln -fs /usr/local/vscode/bin/* /usr/bin

if [[ $1 == "-ri" ]]; then
    mv /tmp/user /usr/local/vscode
    mv /tmp/exts /usr/local/vscode
fi

if [[ ! -d /usr/local/vscode/user/User/Workspaces ]] || [[ ! -f /usr/local/vscode/user/User/Workspaces/main.code-workspace ]]; then
    mkdir /usr/local/vscode/user
    mkdir /usr/local/vscode/user/User
    mkdir /usr/local/vscode/user/User/Workspaces
    curl https://scripts.justman10000.de/assets/main.code-workspace -o /usr/local/vscode/user/User/Workspaces/main.code-workspace
fi

if ! [[ -f /etc/systemd/system/vscode.service ]] && [[ $1 != "-ri" ]]; then
    msd -c vscode "code-server --bind-addr 0.0.0.0:8932 /usr/local/vscode/user/User/Workspaces/main.code-workspace"

    systemctl enable vscode.service
fi

sed -i "s/$(grep 'password:' /root/.config/code-server/config.yaml)/password: 1/g" /root/.config/code-server/config.yaml

msd -s vscode

cat << EOF
# Go now to $(curl -s4 ifconfig.me):8932
Password = 1
EOF

cat << 'EOF' > /home/insExts.sh
# Now, paste this (in an terminal of VSCode, not in the native terminal)
# To use the multi folder view
# code-server -r /usr/local/vscode/user/User/Workspaces/main.code-workspace
# Execute then `bash /home/insExts.sh`
exts=(
    cweijan.vscode-database-client2
    GitHub.vscode-github-actions
    GitHub.github-vscode-theme
    GitHub.vscode-pull-request-github
    MS-CEINTL.vscode-language-pack-de
    ms-azuretools.vscode-docker
    RoweWilsonFrederiskHolme.wikitext
)

for ext in ${exts[@]}; do
    code-server --install-extension $ext
done
EOF

systemctl start vscode.service
journalctl -f -u vscode.service