#!/bin/bash

set -e

os=""
arch=""

get_os() {
    case $(uname -s) in
        Linux|linux) os=linux ;;
        Darwin|darwin) os=darwin ;;
        *) os= ;;
    esac

    if [ -z "$os" ]; then
        echo "OS $(uname -s) not supported." >&2
        exit 1
    fi
}

get_arch() {
    case $(uname -m) in
        amd64|x86_64) arch=amd64 ;;
        arm64|aarch64) arch=arm64 ;;
        *) arch= ;;
    esac

    if [ -z "$arch" ]; then
        echo "Architecture  $(uname -m) not supported." >&2
        exit 1
    fi
}

check_depends() {
    command -v curl >/dev/null || {
        echo "Dependency check failed: please install 'curl' before proceeding."
        exit 1
    }

    command -v go >/dev/null || {
        echo "Dependency check failed: please install 'go' before proceeding."
        exit 1
    }

    [[ ":$PATH:" == *"$(go env GOPATH)/bin"* ]] || {
        echo "Dependency check failed: please add $(go env GOPATH)/bin to your PATH env before proceeding."
        exit 1
    }
}

install_binary() {
    install_dir=$(go env GOPATH)/bin
    install_path=$(go env GOPATH)/bin/tcctl

    mkdir -p $install_dir
    curl -o $install_path http://fileserver.pingcap.net/download/pingcap/qa/test-infra/tcctl-$os-$arch
    chmod 755 $install_path
}

get_os
get_arch
check_depends
install_binary
