#! /usr/bin/env nix-shell
#! nix-shell -i nix -p nix
#! nix shell nixpkgs#bash nixpkgs#dotnet-ef nixpkgs#postgresql nixpkgs#nodejs nixpkgs#dos2unix --command bash

set -ex
rm -rfv Models/Spacebar.Models.Db

# prep temporary db
# - Update collation version for template1 just incase!
psql -U postgres -c 'ALTER DATABASE template1 REFRESH COLLATION VERSION;'
dropdb -U postgres sb-server-scaffold --if-exists --force || true
createdb -U postgres sb-server-scaffold
# - Build spacebar-ts and apply it's migrations
pushd ../..
npm run build:src:tsgo
DATABASE=postgres://postgres@127.0.0.1/sb-server-scaffold npm run apply:migrations
popd

# Create new project
pushd Models
dotnet new classlib --no-restore -o Spacebar.Models.Db
pushd Spacebar.Models.Db
rm Class1.cs
dotnet add package Npgsql.EntityFrameworkCore.PostgreSQL -n -f net10.0
dotnet add package Microsoft.EntityFrameworkCore.Design -n -f net10.0

dotnet build

dotnet-ef dbcontext scaffold "Host=127.0.0.1; Username=postgres; Database=sb-server-scaffold" \
  Npgsql.EntityFrameworkCore.PostgreSQL \
  -o Models \
  -c SpacebarDbContext \
  --context-dir Contexts \
  --force \
  --no-onconfiguring \
  --data-annotations \
  --no-build


echo 'Patching results...'

for f in **/*.cs; do
  dos2unix --verbose --keepdate "$f"
done

for patch in ../db-patches/*.patch; do
  patch --verbose -p2 < $patch
done

echo '[]' > deps.json
git add .
popd
popd
echo 'Updating deps.json...'
./update-deps.cs Spacebar-Models-Db

echo 'Scaffolded database and applied patches. Dont forget to generate new patches with `cd Models && git diff --relative Spacebar.Models.Db/path/xyz > db-patches/001-your-patch-name.patch!`'
