#!/bin/bash

ti:compname() {
  echo "$1-$2-$(go env GOOS)-$(go env GOARCH)"
}

ti:tiuppublish() {
    source ~/.bash_profile
    if ! hash tiup; then
        curl --proto '=https' --tlsv1.2 -sSf https://tiup-mirrors.pingcap.com/install.sh | sh
        source ~/.bash_profile
    fi

    local TIUP_MIRROR
    TIUP_MIRROR=$1
    mkdir -p ~/.tiup/keys
    curl -sL -o ~/.tiup/keys/private.json $TIUP_MIRROR/private/private.json
    rm -r ~/.tiup/manifests

    local comp_name
    local version
    local tarball
    local entry
    comp_name=$2
    version=$3
    tarball=$4
    entry=$5

    tiup mirror publish $comp_name $version $tarball $entry \
    --arch $(go env GOARCH) --os $(go env GOOS) --endpoint $TIUP_MIRROR
}

ti:package() {
  local name
  name=$(ti:compname "$1" "$2")
  shift; shift
  tar -zcf "$name.tar.gz" "$@"
  sha1sum < "$name.tar.gz" | awk '{print $1}' > "$name.sha1"
  echo "$name.tar.gz"
}

ti:upload() {
  curl -s -F "$2=@$1" fileserver.pingcap.net/upload > /dev/null
  echo "http://fileserver.pingcap.net/download/$2"
  if [ -f "${1%.tar.gz}.sha1" ]; then
    curl -s -F "${2%.tar.gz}.sha1=@${1%.tar.gz}.sha1" fileserver.pingcap.net/upload > /dev/null
  elif [ -f "${1%.*}.sha1" ]; then
    curl -s -F "${2%.*}.sha1=@${1%.*}.sha1" fileserver.pingcap.net/upload > /dev/null
  fi
}

ti:publish() {
  local publish=$1
  shift

  local mirror
  local entry
  local path
  local comp
  local ver
  local pkg
  mirror=$1
  entry=$2
  path=$3
  comp=$4
  ver=$5
  shift 5

  pkg=$(ti:package "$comp" "$ver" "$@")
  ti:upload "$pkg" "$path/$pkg"

  if [[ $publish -eq "true" ]]; then
    ti:tiuppublish "$mirror" "$comp" "$ver" "$pkg" "$entry" 1>./tiup_publish.log 2>tiup_publish.err
  fi
}

cmd=$1; shift
case $cmd in
compname)
  ti:compname "$@"
  ;;
package)
  ti:package "$@"
  ;;
upload)
  ti:upload "$@"
  ;;
publish)
  ti:publish "$@"
  ;;
tiup_publish)
  ti:tiuppublish "$@"
  ;;
*)
  echo "HELP: tici.sh (compname|package|publish|upload)"
  ;;
esac
