#!/bin/bash
set -e

web_only=false
dotnet_only=false
skip_tests=false

while test $# -gt 0; do
  case "$1" in
    -h|--help)
      echo 'options:'
      echo '-h, --help          show help'
      echo '--web-only          skip dotnet build'
      echo '--dotnet-only       skip web build'
      echo '--skip-tests        skip execution of npm and dotnet tests'
      echo '--version           version for the binary. defaults to current git tag+SHA'
      exit 0
      ;;
    --web-only)
      web_only=true
      shift
      ;;
    --dotnet-only)
      dotnet_only=true
      shift
      ;;
    --skip-tests)
      skip_tests=true
      shift
      ;;
    --version)
      shift
      version=$1
      shift
      ;;
    *)
      break
      ;;
  esac
done

if [ -z "$version" ]; then 
  tag=$(git describe --tags --abbrev=0)
  sha=$(git rev-parse --short HEAD)
  version=$tag+$sha
fi

if [ "$dotnet_only" == true ]; then
  echo $'\n\t⏩  web build skipped\n'
else 
  # build web
  cd src/web
  echo $'\n\t📍  '$(pwd)$'\n'

  echo $'\n\t🛠️  npm ci\n'
  npm ci

  if [ "$skip_tests" == true ]; then
      echo $'\n\t⏩  web tests skipped\n'
  else
      echo $'\n\t🧪  npm run test-unattended\n'
      npm run test-unattended
  fi

  echo $'\n\t🛠️  npm run build\n'
  npm run build

  if [ "$web_only" == false ]; then
    # remove old build, but keep .gitkeep
    rm -rf ../slskd/wwwroot
    mkdir ../slskd/wwwroot
    touch ../slskd/wwwroot/.gitkeep

    # copy new files
    echo $'\n\t🛠️  cp -r build/* ../slskd/wwwroot/\n'
    cp -r build/* ../slskd/wwwroot/
  fi
  
  cd ../..
fi

if [ "$web_only" == true ]; then
    echo $'\n\t⏩  dotnet build skipped\n'
else
    # build api + web
    cd src/slskd
    echo $'\n\t📍 '$(pwd)$'\n'

    echo $'\n\t🛠️  dotnet build --no-incremental --nologo --configuration Release -p:Version '$version$'\n'
    dotnet build --no-incremental --nologo --configuration Release -p:Version=$version

    if [ "$skip_tests" == true ]; then
        echo $'\n\t⏩  dotnet tests skipped\n'
    else
        echo $'\n\t🧪  dotnet test --configuration Release ../../tests/slskd.Tests.Unit\n'
        dotnet test --configuration Release ../../tests/slskd.Tests.Unit

        echo $'\n\t🧪  dotnet test --configuration Release ../../tests/slskd.Tests.Integration\n'
        dotnet test --configuration Release ../../tests/slskd.Tests.Integration
    fi
fi

echo $'\n\t🎉  build succeded!\n'