#!/bin/bash

VERSION=$1
OS=$2
ARCH=$3

BASE_PATH=~/.local/share/godev
LINK_PATH=$BASE_PATH/go
TARGET_PATH=$BASE_PATH/version/$VERSION

if [ ! $OS ]
then
    OS=linux
fi

if [ ! $Arch ]
then
    Arch=amd64
fi

if [ ! $VERSION ]
then
    echo 'version param not found, version list: '
    ls -l $BASE_PATH/version | grep -v total  | awk '{print $9}' 
    echo 'use godev.sh {version} to use'
    exit 0
fi



if [ -d $TARGET_PATH ]
then
    echo "go-$VERSION is found in local path, check in......"
    rm -f $LINK_PATH && ln -s $TARGET_PATH $LINK_PATH
    echo 'finish, now go version: '
    go version
    exit 0
fi

echo "go-$VERSION is not found, installing version $VERSION ....."

FileName=go${VERSION}.${OS}-${Arch}.tar.gz
Url=https://go.dev/dl/$FileName
# Url=https://mirrors.ustc.edu.cn/golang/$FileName
Workdir=/tmp/zeus/worker/go-install

echo "download url: $Url"
echo "workdir: $Workdir"

# download go version
mkdir -p $BASE_PATH/path/bin && \
mkdir -p $BASE_PATH/path/src && \
mkdir -p $BASE_PATH/path/pkg && \
mkdir -p $BASE_PATH/version/ && \
mkdir -p $Workdir && \
wget -P $Workdir $Url && \
tar -zxf $Workdir/$FileName && \
rm -rf $TARGET_PATH && \
mv go $TARGET_PATH

if [ $? != 0 ]
then
    exit $?
fi

# link go version
# https://go.dev/dl/
rm -f $LINK_PATH && ln -s $TARGET_PATH $LINK_PATH
echo 'finish, now go version: '
go version

echo -e 'using command to set environment: '
echo -e "go env -w GOROOT=$LINK_PATH"
echo -e "go env -w GOPATH=$BASE_PATH/path"
echo -e "go env -w GO111MODULE=on"
echo -e "go env -w GOPROXY=https://goproxy.cn,direct"