-- ScadaLink env2 database setup
-- Creates env2 logical databases on an existing scadalink-mssql instance.
-- Idempotent: re-runs are no-ops. Assumes setup.sql has already run
-- (i.e. the scadalink_app login already exists).

-- Create env2 databases
IF NOT EXISTS (SELECT name FROM sys.databases WHERE name = 'ScadaLinkConfig2')
    CREATE DATABASE ScadaLinkConfig2;
GO

IF NOT EXISTS (SELECT name FROM sys.databases WHERE name = 'ScadaLinkMachineData2')
    CREATE DATABASE ScadaLinkMachineData2;
GO

-- Grant db_owner on ScadaLinkConfig2
USE ScadaLinkConfig2;
GO
IF NOT EXISTS (SELECT name FROM sys.database_principals WHERE name = 'scadalink_app')
    CREATE USER scadalink_app FOR LOGIN scadalink_app;
GO
ALTER ROLE db_owner ADD MEMBER scadalink_app;
GO

-- Grant db_owner on ScadaLinkMachineData2
USE ScadaLinkMachineData2;
GO
IF NOT EXISTS (SELECT name FROM sys.database_principals WHERE name = 'scadalink_app')
    CREATE USER scadalink_app FOR LOGIN scadalink_app;
GO
ALTER ROLE db_owner ADD MEMBER scadalink_app;
GO
