using System.Diagnostics; using System.Text.Json; using Dapper; using Microsoft.Data.SqlClient; internal static class MapStoryDevFixture { public static async Task RunAsync(string[] args) { if(!OperatingSystem.IsLinux()) throw new PlatformNotSupportedException("Development fixtures run on the Linux development host"); if(args.Length!=3 || !args[1].StartsWith("/tmp/pd-dev-browser-") || !args[2].StartsWith("/tmp/pd-dev-browser-")) throw new InvalidOperationException("Use --maps-story-dev-fixture dedicated-identity.json new-fixture.json"); using var identity=JsonDocument.Parse(await File.ReadAllTextAsync(args[1]));var root=identity.RootElement; if(root.GetProperty("Database").GetString()!="PlotDirector_Development" || !root.GetProperty("Email").GetString()!.StartsWith("pwa-browser-")) throw new InvalidOperationException("Dedicated Development identity required"); var start=new ProcessStartInfo("sudo"){RedirectStandardOutput=true,RedirectStandardError=true};foreach(var p in new[]{"-n","cat","/etc/plotdirector/plotdirector.env"})start.ArgumentList.Add(p); using var process=Process.Start(start)!;var env=await process.StandardOutput.ReadToEndAsync();await process.WaitForExitAsync();if(process.ExitCode!=0)throw new InvalidOperationException("Development configuration unavailable"); var raw=env.Split('\n').Single(l=>l.StartsWith("ConnectionStrings__DefaultConnection=")).Split('=',2)[1].Trim().Trim('\"','\''); if(new SqlConnectionStringBuilder(raw).InitialCatalog!="PlotDirector_Development")throw new InvalidOperationException("Wrong database"); using var db=new SqlConnection(raw);await db.OpenAsync();if(await db.ExecuteScalarAsync("SELECT DB_NAME()")!="PlotDirector_Development")throw new InvalidOperationException("Wrong database"); var userID=root.GetProperty("UserID").GetInt32();if(!await db.ExecuteScalarAsync("SELECT CONVERT(bit,CASE WHEN EXISTS(SELECT 1 FROM dbo.AppUser WHERE UserID=@userID AND Email=@email) THEN 1 ELSE 0 END)",new{userID,email=root.GetProperty("Email").GetString()}))throw new InvalidOperationException("Fixture identity mismatch"); // Provisioning follows an explicit copy-only backup just like migrations; no existing manuscript is edited. var backup=$"/var/opt/mssql/backup/maps-story-fixture-{DateTime.UtcNow:yyyyMMddTHHmmss}-{Guid.NewGuid():N}.bak"; await db.ExecuteAsync("BACKUP DATABASE [PlotDirector_Development] TO DISK=@backup WITH COPY_ONLY,CHECKSUM",new{backup},commandTimeout:180); var file=new FileInfo(backup.Replace("/var/opt/mssql/","/sql/mssql/"));if(!file.Exists||file.Length==0)throw new InvalidOperationException("Backup file missing"); using var rows=await db.QueryMultipleAsync(await File.ReadAllTextAsync("PlotLine.Tests/Sql/210_MapStoryFixture.sql"),new{UserID=userID},commandTimeout:180); object? fixture=null;while(!rows.IsConsumed)foreach(var row in await rows.ReadAsync())if(((IDictionary)row).ContainsKey("MapID"))fixture=row; if(fixture is null)throw new InvalidOperationException("Fixture was not returned"); await using var output=new FileStream(args[2],new FileStreamOptions{Mode=FileMode.CreateNew,Access=FileAccess.Write,UnixCreateMode=UnixFileMode.UserRead|UnixFileMode.UserWrite});await JsonSerializer.SerializeAsync(output,fixture); Console.WriteLine("Dedicated Maps Story fixture created in Development; private fixture IDs written. Cleanup uses the dedicated identity's normal account deletion workflow."); } public static async Task DatabaseAsync() { if(!OperatingSystem.IsLinux())throw new PlatformNotSupportedException(); var start=new ProcessStartInfo("sudo"){RedirectStandardOutput=true,RedirectStandardError=true};foreach(var p in new[]{"-n","cat","/etc/plotdirector/plotdirector.env"})start.ArgumentList.Add(p); using var process=Process.Start(start)!;var env=await process.StandardOutput.ReadToEndAsync();await process.WaitForExitAsync();if(process.ExitCode!=0)throw new InvalidOperationException("Development configuration unavailable"); var raw=env.Split('\n').Single(l=>l.StartsWith("ConnectionStrings__DefaultConnection=")).Split('=',2)[1].Trim().Trim('\"','\''); if(new SqlConnectionStringBuilder(raw).InitialCatalog!="PlotDirector_Development")throw new InvalidOperationException("Wrong database"); using var db=new SqlConnection(raw);await db.OpenAsync();if(await db.ExecuteScalarAsync("SELECT DB_NAME()")!="PlotDirector_Development")throw new InvalidOperationException("Wrong database"); var userID=await db.ExecuteScalarAsync("SELECT TOP(1) UserID FROM dbo.ProjectUserAccess WHERE IsActive=1 AND AccessRole='Owner'"); var sql="BEGIN TRAN;\n"+await File.ReadAllTextAsync("PlotLine.Tests/Sql/210_MapStoryFixture.sql")+"\n"+await File.ReadAllTextAsync("PlotLine.Tests/Sql/210_MapStoryAssertions.sql"); using var rows=await db.QueryMultipleAsync(sql,new{UserID=userID},commandTimeout:180); var passed=false;while(!rows.IsConsumed)foreach(var row in await rows.ReadAsync()){var values=(IDictionary)row;if(values.TryGetValue("Result",out var message)){Console.WriteLine(message);passed=true;}} if(!passed)throw new InvalidOperationException("No database assertion result returned"); } }