#! /bin/bash

function main() {
   cd "$(dirname "$BASH_SOURCE")"
   local exec="$(basename "$PWD")"
   set -e
   if [ -z "$NOTEST" ]; then
      go test ./...
   fi
   GOOS=linux GOARCH=arm GOARM=5 gobuild $exec
   for authed in dndex; do # dndex-auth; do
      scp ./public/swagger/* zach@tickle.lan:./$authed/files/swagger/
      scp $exec zach@tickle.lan:./$authed/dndex.new
      ssh zach@tickle.lan bash -c "true; while [ -e ./$authed/dndex.new ]; do printf '.'; sleep 3; done; echo"
   done &
   wait
   GOOS=linux gobuild $exec
   echo scp $exec bel@remote.blapointe.com:/home/bel/services/bin/dndex.new
   echo ssh bel@remote.blapointe.com bash -c 'true; md5sum ./services/bin/dndex*; while [ -e ./services/bin/dndex.new ]; do printf "."; sleep 3; done; md5sum ./services/bin/dndex*'
   rm $exec
   if [ -n "$BIG" ]; then
      big
   fi
}

function gobuild() {
   CGO_ENABLED=0 go build \
      -o $1 \
      -a \
      -installsuffix cgo \
      -ldflags "-s -w -X main.GitCommit=$(
         (
            git rev-list -1 HEAD
            if git diff | grep . > /dev/null; then
               echo "-dirty"
            fi
         ) | tr -d '\n'
      )"
}

function big() {
   pushd ./public/vue/dndex-ui
   git checkout master
   git pull origin master
   npm install
   npm run build
   ssh zach@tickle.lan rm -rf ./dndex-ui/public
   scp -r ./dist zach@tickle.lan:./dndex-ui/public
   popd
}

if [ "$0" == "$BASH_SOURCE" ]; then
   main "$@"
fi
