#!/bin/bash
# Copyright 2017 Istio Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
################################################################################

# bazel's go_binary cross-compilation isn't ready (see
# github.com/bazelbuild/rules_go/issues/70). Use normal golang toolchain to
# cross compile istioctl for windows and osx.

set -o errexit
set -o nounset
set -o pipefail
set -x

ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd -P)"
DIR_NAME="$(basename ${ROOT})"
BIN_DIR='.'
BUCKET_PATH=''
RELEASE=false
OUTPUT_DIR=""

function cleanup {
  rm -rf "${BIN_DIR}"
}

cd $ROOT
while getopts :o:p:r arg; do
  case ${arg} in
    o) OUTPUT_DIR="${OPTARG}"
       BIN_DIR="$(mktemp -d /tmp/istioctl.XXXX)"
       ;;
    p)
      BUCKET_PATH="${OPTARG}"
      BIN_DIR="$(mktemp -d /tmp/istioctl.XXXX)"
      ;;
    r) RELEASE=true;;
    *) error_exit "Unrecognized argument -${OPTARG}";;
  esac
done

[[ "${BIN_DIR}" != '.' ]] && trap cleanup exit

cp -f "${ROOT}/../bazel-bin/pilot/cmd/istioctl/istioctl" "${BIN_DIR}/istioctl-linux"

if [[ ${RELEASE} == true ]]; then

  # set linker flags for populating version info
  LDFLAGS=""
  while read line; do
    read SYMBOL VALUE < <(echo $line)
    LDFLAGS=${LDFLAGS}" -X istio.io/istio/pilot/tools/version.${SYMBOL}=${VALUE}"
  done < <(../bin/get_workspace_status)

  GOOS=darwin GOARCH=amd64 go build -ldflags "${LDFLAGS}" istio.io/istio/pilot/cmd/istioctl
  mv istioctl "${BIN_DIR}/istioctl-osx"

  # install missing spf13/cobra dependency (windows only)
  go get github.com/inconshreveable/mousetrap
  GOOS=windows GOARCH=amd64 go build -ldflags "${LDFLAGS}" istio.io/istio/pilot/cmd/istioctl
  mv istioctl.exe "${BIN_DIR}/istioctl-win.exe"
fi
if [[ -n "${BUCKET_PATH}" ]]; then
  gsutil -m cp -r "${BIN_DIR}"/istioctl-* "${BUCKET_PATH}/" \
    || { echo "Failed to upload binaries to ${BUCKET_PATH}"; exit 1; }
fi

if [[ "${OUTPUT_DIR}" != "" ]]; then
  cp "${BIN_DIR}"/istioctl-* "${OUTPUT_DIR}/"
fi
