export GO111MODULE=on
export GOPATH=/opt/go
export PATH=$GOPATH/bin:$PATH
export PATH=/usr/lib/go-1.18/bin:$PATH

BDIR=/opt/go

REPO_PATH=$(pwd)
REPO_DIR=$(basename "$REPO_PATH")

[ -z "$MVO_BRANCH" ] && echo ENOENV && exit 1

### BUILD ###
echo "==> Build $MVO_REPO:$MVO_BRANCH"
echo "COMMIT_AUTHOR:	$MVO_COMMIT_AUTHOR"
echo "COMMIT_MESSAGE:	$MVO_COMMIT_MESSAGE"
pwd
ln -sf $(pwd) $BDIR/src/$REPO_DIR
cd $BDIR/src/$REPO_DIR
pwd
echo " -> $MVO_REPO"
go get
go build
# upx -q --no-color --no-progress $MVO_REPO |grep "$MVO_REPO\$"
echo

### DEPLOY ###
cd $BDIR/src/$REPO_DIR
pwd
if [ "$MVO_BRANCH" = "dev" ]; then
  echo "==> Install APPs on builder"
  echo " -> $MVO_REPO"
  [ -f $BDIR/bin/$MVO_REPO ] && mv -v $BDIR/bin/$MVO_REPO $BDIR/bin/$MVO_REPO.old
  install -m 755 $MVO_REPO $BDIR/bin/$MVO_REPO
  ls -lh $BDIR/bin/$MVO_REPO
  echo

  echo "==> Restart $MVO_REPO service on builder"
  echo " -> $MVO_REPO"
  sudo /bin/systemctl restart $MVO_REPO
  for i in $(pgrep -x $MVO_REPO); do ps ax |grep "$i" |grep -v grep; done
  echo

elif [ "$MVO_BRANCH" = "master" ]; then
  for srv in web5 web4; do
    echo "==> Install APPs on $srv"
    SSH="ssh -p 3301 $srv"
    echo " -> $MVO_REPO"
    $SSH "test -f $BDIR/bin/$MVO_REPO && mv -v $BDIR/bin/$MVO_REPO $BDIR/bin/$MVO_REPO.old"
    scp -P 3301 $MVO_REPO $srv:$BDIR/bin/$MVO_REPO
    $SSH "chmod +x $BDIR/bin/$MVO_REPO"
    $SSH "ls -lh $BDIR/bin/$MVO_REPO"
    echo
  
    echo "==> Restart MVO_REPO service on $srv"
    echo " -> $MVO_REPO"
    $SSH "sudo /bin/systemctl restart $MVO_REPO"
    $SSH "for i in \$(pgrep -x $MVO_REPO); do ps ax |grep \"\$i\" |grep -v grep; done"
    echo
  done
fi

cd
rm $BDIR/src/$REPO_DIR

echo DONE

