#!/usr/bin/env bash

set -euo pipefail

echo '**** Set System Proxy ****'

cat >> ~/.bashrc <<EOF
alias proxy='export https_proxy=http://192.168.100.22:7893 http_proxy=http://192.168.100.22:7893 all_proxy=socks5://192.168.100.22:7893'
alias unproxy='unset {http,https,all}_proxy'
EOF

source ~/.bashrc

proxy

cat >> ~/.bashrc <<'EOF'
function parse_git_url() {
    # https://git-scm.com/docs/git-clone#_git_urls

    local path=$1

    # 去掉协议 http:// ssh:// ftp://
    if [[ $path =~ ^[A-Za-z]+:// ]]; then
        local proto="${BASH_REMATCH[0]}"
        path=${path:${#proto}}
    fi

    # 去掉用户和密码 git:pass@
    local index=$(expr index "$path" "@")
    if [[ $index -gt 0 ]]; then
        path=${path:index}
    fi

    # 获取域名
    index=$(expr index "$path" ":")
    separator_index=$(expr index "$path" "/")
    if [[ $index -gt 0 ]]; then
        # 冒号前为域名
        local host=${path:0:index-1}
        # 冒号后为端口或用户名
        local len=`expr $separator_index - $index - 1`
        local user=${path:index:len}
        # 如果是纯数字则为端口号
        if [[ $user =~ ^[0-9]+$ && $user -le 65545 ]]; then
            user=''
        fi
    else
        # 第一个 / 前为域名
        local host=${path:0:separator_index-1}
    fi

    # 截断已处理的部分
    path=${path:separator_index}

    if [[ -z "$user" ]]; then
        # 第二个 / 前为用户名
        index=$(expr index "$path" "/")
        local user=${path:0:index-1}
        path=${path:index}
    fi

    # 去掉 .git 后缀
    if [[ $path =~ \.git$ ]]; then
        path=${path:0:-4}
    fi

    echo $host $user $path
}

function gitclone() {
    local BASE_PATH=${DEFAULT_WORKSPACE:-${HOME}/workspace}

    local repository=$1
    if [[ -z $repository ]]; then
        echo "No repository specified"
        return 1
    fi

    local array=(`parse_git_url $repository`)
    local host="${array[0]}"
    local user="${array[1]}"
    local repo="${array[2]}"

    if [[ -z "$host" || -z "$user" || -z "$repo" ]]; then
        echo "Unable to extract author/repository information"
        return 1
    fi

    local directory="$BASE_PATH/$host/$user/$repo"
    if [[ -d $directory ]]; then
        echo "Directory exits: $directory"

        local choice
        read -p "Force clone? [y/N]: " choice
        if [[ $choice != "y" && $choice != "Y" ]]; then
            echo "Abort."
            return 1
        fi
    fi

    shift 1

    echo git clone $@ $repository $BASE_PATH/$host/$user/$repo

    return $?
}
EOF

source ~/.bashrc


echo '**** Set Git Config ****'

git config --global user.name "liweitao"

git config --global user.email "li876576706@163.com"

git config --global credential.helper store




echo '**** Install Git LFS ***'

cd /tmp

curl -o git-lfs.tgz -C - -L https://github.com/git-lfs/git-lfs/releases/download/v3.5.1/git-lfs-linux-amd64-v3.5.1.tar.gz

mkdir git-lfs

tar --extract --file git-lfs.tgz --strip-components 1 --directory git-lfs

bash ./git-lfs/install.sh --local

git lfs --version



echo '**** Install Hugo ****'

cd /tmp

curl -o hugo.tgz -C - -L https://github.com/gohugoio/hugo/releases/download/v0.123.8/hugo_extended_0.123.8_linux-amd64.tar.gz

mkdir hugo

tar --extract --file hugo.tgz --strip-components 1 --directory hugo

mv -vT hugo/hugo ~/.local/bin/hugo

hugo version



echo '**** Install Python ****'

cd /tmp

# https://devguide.python.org/getting-started/setup-building/#install-dependencies
curl -o python.tgz -C - -L https://www.python.org/ftp/python/3.12.2/Python-3.12.2.tgz

mkdir python

tar --extract --file python.tgz --strip-components 1 --directory python

cd python

sudo apt update

# https://devguide.python.org/getting-started/setup-building/#install-dependencies
sudo apt-get install -y build-essential gdb lcov pkg-config \
      libbz2-dev libffi-dev libgdbm-dev libgdbm-compat-dev liblzma-dev \
      libncurses5-dev libreadline6-dev libsqlite3-dev libssl-dev \
      lzma lzma-dev tk-dev uuid-dev zlib1g-dev

./configure --prefix="$HOME/.local/"

make -j8

make install

echo 'export PATH=~/.local/bin:$PATH' >> ~/.bashrc

source ~/.bashrc

ln -sv ~/.local/bin/python3 ~/.local/bin/python

ln -sv ~/.local/bin/pip3 ~/.local/bin/pip

python -V

pip -V



echo '**** Install Golang ****'

cd /tmp

curl -o go.tgz -C - -L https://go.dev/dl/go1.22.1.linux-amd64.tar.gz

tar -zxvf go.tgz -C ~/.local/lib

ln -sv /config/.local/lib/go/bin/go /config/.local/bin/go

ln -sv /config/.local/lib/go/bin/gofmt /config/.local/bin/gofmt

echo 'export GOROOT=~/.local/lib/go' >> ~/.bashrc

source ~/.bashrc

go version

go env -w GOPROXY=https://goproxy.cn,direct



echo '**** Install Rust ****'

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

. "$HOME/.cargo/env"

rustc -V

cargo -V



echo '**** Install Ruby ****'

cd /tmp

curl -o ruby.tgz -C - -L https://cache.ruby-lang.org/pub/ruby/3.3/ruby-3.3.0.tar.gz

mkdir ruby

tar --extract --file ruby.tgz --strip-components 1 --directory ruby

cd ruby

sudo apt update

sudo apt install -y git-core curl zlib1g-dev build-essential libssl-dev libreadline-dev libyaml-dev libsqlite3-dev sqlite3 libxml2-dev libxslt1-dev libcurl4-openssl-dev libffi-dev

./configure --prefix="$HOME/.local/"

make -j8

make install

ruby -v



echo '**** Install Java ****'

cd /tmp

sudo apt-get install -y zip unzip

curl -s "https://get.sdkman.io" | bash

source "/config/.sdkman/bin/sdkman-init.sh"

sdk version

sdk install java 21-graalce && sdk default java 21-graalce

java --version

# https://github.com/Homebrew/homebrew-core/blob/HEAD/Formula/m/mvnvm.rb
curl -o mvnvm.tgz -C - -L https://bitbucket.org/mjensen/mvnvm/get/mvnvm-1.0.26.tar.gz

mkdir -p ~/.local/lib/mvnvm

tar --extract --file mvnvm.tgz --strip-components 1 --directory ~/.local/lib/mvnvm

ln -sv /config/.local/lib/mvnvm/mvn /config/.local/bin/mvn

ln -sv /config/.local/lib/mvnvm/mvnDebug /config/.local/bin/mvnDebug

mvn --mvnvm-version

cat >> ~/.mvnvm.properties <<EOF
mvn_version=3.9.6
central_uri=https://repo.huaweicloud.com/repository/maven/
EOF

mvn -v

mkdir ~/.m2

cp /config/.mvnvm/apache-maven-3.9.6/conf/settings.xml ~/.m2/settings.xml

sed -i '/<mirrors>/a\    <mirror>\n      <id>huaweicloud-public</id>\n      <mirrorOf>central,jcenter</mirrorOf>\n      <name>华为云公共仓库</name>\n      <url>https://repo.huaweicloud.com/repository/maven/</url>\n    </mirror>' ~/.m2/settings.xml



echo '**** Install Csharp ****'

sudo apt install -y libicu70

# https://learn.microsoft.com/zh-cn/dotnet/core/install/linux-scripted-manual#scripted-install
curl -sL https://dot.net/v1/dotnet-install.sh | bash

cat >> ~/.bashrc <<"EOF"
export DOTNET_ROOT=$HOME/.dotnet
export PATH=$PATH:$DOTNET_ROOT:$DOTNET_ROOT/tools

# bash parameter completion for the dotnet CLI

function _dotnet_bash_complete()
{
  local cur="${COMP_WORDS[COMP_CWORD]}" IFS=$'\n' # On Windows you may need to use use IFS=$'\r\n'
  local candidates

  read -d '' -ra candidates < <(dotnet complete --position "${COMP_POINT}" "${COMP_LINE}" 2>/dev/null)

  read -d '' -ra COMPREPLY < <(compgen -W "${candidates[*]:-}" -- "$cur")
}

complete -f -F _dotnet_bash_complete dotnet
EOF

source ~/.bashrc

dotnet --version



echo '**** Install Node ****'

curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.7/install.sh | bash

cat >> ~/.bashrc << "EOF"
export NVM_DIR="$HOME/.nvm"
[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh"  # This loads nvm
[ -s "$NVM_DIR/bash_completion" ] && \. "$NVM_DIR/bash_completion"  # This loads nvm bash_completion
EOF

source ~/.bashrc

command -v nvm

nvm ls-remote

nvm install v18.19.1

node -v

npm -v



echo '**** Install Docker cli ****'

cd /tmp

# https://github.com/docker-library/docker/blob/master/25/cli/Dockerfile
curl -o docker.tgz -C - -L https://download.docker.com/linux/static/stable/x86_64/docker-25.0.4.tgz

tar --extract --file docker.tgz --strip-components 1 --directory ~/.local/bin/

docker version

curl -o docker-buildx -C - -L https://github.com/docker/buildx/releases/download/v0.13.0/buildx-v0.13.0.linux-amd64

chmod +x docker-buildx

mkdir -p ~/.docker/cli-plugins

mv -vT docker-buildx ~/.docker/cli-plugins/docker-buildx

docker buildx version

curl -o docker-compose -C - -L https://github.com/docker/compose/releases/download/v2.24.7/docker-compose-linux-x86_64

chmod +x docker-compose

mkdir -p ~/.docker/cli-plugins

mv -vT docker-compose ~/.docker/cli-plugins/docker-compose

ln -sv ~/.docker/cli-plugins/docker-compose ~/.local/bin/docker-compose

docker compose version

docker-compose version



echo '**** Install VsCode Extensions ****'

plugins=(
batisteo.vscode-django
chadalen.vscode-jetbrains-icon-theme
donjayamanne.githistory
donjayamanne.python-environment-manager
donjayamanne.python-extension-pack
eamodio.gitlens
golang.go
kevinrose.vsc-python-indent
mhutchie.git-graph
mobalic.jetbrains-new-dark
ms-azuretools.vscode-docker
ms-ceintl.vscode-language-pack-zh-hans
ms-dotnettools.csharp
ms-dotnettools.vscode-dotnet-runtime
ms-python.debugpy
ms-python.python
ms-python.vscode-pylance
njpwerner.autodocstring
redhat.java
rust-lang.rust-analyzer
tabnine.tabnine-vscode
visualstudioexptteam.intellicode-api-usage-examples
visualstudioexptteam.vscodeintellicode
vmware.vscode-boot-dev-pack
vmware.vscode-spring-boot
vscjava.vscode-java-debug
vscjava.vscode-java-dependency
vscjava.vscode-java-pack
vscjava.vscode-java-test
vscjava.vscode-maven
vscjava.vscode-spring-boot-dashboard
vscjava.vscode-spring-initializr
vue.volar
wholroyd.jinja
)

IFS=$'\n\t'
for plugin in ${plugins[@]}; do
  code-server --install-extension $plugin
done



echo "**** Cleanup ****"

sudo apt-get autoremove

sudo apt-get clean


echo '**** Done ****'
