#!/usr/bin/env bash
# build_go 1.3.1
# Generic script to compile Go programs

set -euo pipefail  # Fail immediately on any error
Gre='\e[1;32m' Red='\e[1;31m' Mag='\e[1;35m' Yel='\e[1;33m' Blu='\e[1;34m' Rst='\e[0m'

# ==== main
Prg=`head -1 go.mod | awk -F'/' '{print $NF}' | awk '{print $NF}'`
case "$OSTYPE" in
    "linux-gnu"* ) printf "==> Linux\n" && BIN=$GOPATH/bin/${Prg} ;;
    "darwin"* )    printf "==> macOS\n" && BIN=$GOPATH/bin/${Prg} ;;
    "msys"* )      printf "==> Windows with GitBASH\n" && BIN=$GOPATH/bin/${Prg}.exe ;;
    * )            printf "==> Unknown OS '$OSTYPE'. Aborting.\n" && exit 1 ;;
esac

echo "==> go mod tidy"
go mod tidy
echo "==> go fmt"
go fmt
echo "==> go test ./..."
go test ./...
echo "==> Installing/running staticcheck ./..."
go install honnef.co/go/tools/cmd/staticcheck@latest
staticcheck ./...

echo "==> go build -ldflags "-s -w" -o $BIN"
go build -ldflags "-s -w" -o $BIN

# Note: You can cross-compile to another OS/arch using something like below:
# GOOS=linux GOARCH=amd64|arm64   go build -ldflags "-s -w" -o ${Prg}
# GOOS=windows GOARCH=amd64|arm64 go build -ldflags "-s -w" -o ${Prg}.exe
# GOOS=darwin GOARCH=arm64        go build -ldflags "-s -w" -o ${Prg}

printf "\n"
ls -l $GOPATH/bin/$Prg | grep $Prg

printf "\n==> grep replace go.mod:\n$Red$(grep replace go.mod)$Rst"
printf "\n==> grep version in main.go:\n$Gre$(grep 'prgver.*=' main.go || grep 'program_version.*=' main.go)$Rst"
printf "\n==> Last 5 tag versions:\n"
git tag | sort -V | tail -5
CurrentTag=`git tag | sort -V | tail -1`
printf "\n==> To publish, do below one-liner, advancing tag version:\n"
printf "\n    Tag=$CurrentTag && git add . && git commit -m \"x updates\" && git tag \$Tag && git push origin \$Tag && git push\n\n"

exit 0
