@echo off setlocal set "OMEGA1209_SELF=%~f0" set "OMEGA1209_ACTION=%~1" set "OMEGA1209_PATH=%~2" powershell.exe -NoProfile -ExecutionPolicy Bypass -Command "$t=[IO.File]::ReadAllText($env:OMEGA1209_SELF); $m='#'; & ([scriptblock]::Create($t.Substring($t.LastIndexOf($m)+$m.Length)))" set "OMEGA1209_EXIT=%ERRORLEVEL%" if not "%OMEGA1209_EXIT%"=="0" if not "%OMEGA1209_NO_PAUSE%"=="1" pause endlocal & exit /b %OMEGA1209_EXIT% # $ErrorActionPreference = 'Stop' Set-StrictMode -Version Latest [Console]::OutputEncoding = [Text.UTF8Encoding]::new($false) $mode = $env:OMEGA1209_ACTION if ([string]::IsNullOrWhiteSpace($mode)) { $mode = 'apply' } $mode = $mode.TrimStart('/','-').ToLowerInvariant() if ($mode -notin @('apply','apply-only','restore','restore-only','status')) { Write-Host 'Usage: Omega_1209.bat [apply|apply-only|restore|restore-only|status] [Omega folder]' exit 2 } $mutex = [Threading.Mutex]::new($false, 'Local\YGOOmega1209Mode') $locked = $false $db = $null try { try { $locked = $mutex.WaitOne(0) } catch [Threading.AbandonedMutexException] { $locked = $true } if (-not $locked) { throw 'Another Omega-1209 operation is running.' } $root = $env:OMEGA1209_PATH if ([string]::IsNullOrWhiteSpace($root)) { $beside = [IO.Path]::GetDirectoryName($env:OMEGA1209_SELF) if (Test-Path -LiteralPath (Join-Path $beside 'YGO Omega.exe')) { $root = $beside } else { $root = Join-Path $env:LOCALAPPDATA 'Programs\YGO Omega' } } $root = (Resolve-Path -LiteralPath $root).Path $exe = Join-Path $root 'YGO Omega.exe' $files = Join-Path $root 'YGO Omega_Data\Files' $database = Join-Path $files 'Bundles\db' $lists = Join-Path $files 'Banlists' $target = Join-Path $lists '20120901BANLIST.conf' $backup = Join-Path $files 'Backup\1209-mode' $savedDb = Join-Path $backup 'banlists.sqlite' $stateFile = Join-Path $backup 'state.json' $required = @($exe,$database) if ($mode.StartsWith('apply')) { $required += $target } foreach ($f in $required) { if (-not (Test-Path -LiteralPath $f -PathType Leaf)) { throw "Required file missing: $f" } } if ($mode -ne 'status' -and @(Get-Process -Name 'YGO Omega','OmegaUpdater' -ErrorAction SilentlyContinue).Count) { throw 'Close YGO Omega and OmegaUpdater, then run this BAT again. Unsaved decks are never force-closed.' } Add-Type -TypeDefinition @' using System; using System.Runtime.InteropServices; using System.Text; using System.Text.RegularExpressions; public sealed class OmegaSqlite : IDisposable { IntPtr db; [DllImport("winsqlite3.dll", CallingConvention=CallingConvention.Cdecl)] static extern int sqlite3_open_v2(byte[] path, out IntPtr handle, int flags, IntPtr vfs); [DllImport("winsqlite3.dll", CallingConvention=CallingConvention.Cdecl)] static extern int sqlite3_close(IntPtr handle); [DllImport("winsqlite3.dll", CallingConvention=CallingConvention.Cdecl)] static extern IntPtr sqlite3_errmsg(IntPtr handle); [DllImport("winsqlite3.dll", CallingConvention=CallingConvention.Cdecl)] static extern int sqlite3_exec(IntPtr handle, byte[] sql, IntPtr callback, IntPtr arg, out IntPtr error); [DllImport("winsqlite3.dll", CallingConvention=CallingConvention.Cdecl)] static extern void sqlite3_free(IntPtr ptr); [DllImport("winsqlite3.dll", CallingConvention=CallingConvention.Cdecl)] static extern int sqlite3_prepare_v2(IntPtr handle, byte[] sql, int length, out IntPtr stmt, IntPtr tail); [DllImport("winsqlite3.dll", CallingConvention=CallingConvention.Cdecl)] static extern int sqlite3_step(IntPtr stmt); [DllImport("winsqlite3.dll", CallingConvention=CallingConvention.Cdecl)] static extern IntPtr sqlite3_column_text(IntPtr stmt, int col); [DllImport("winsqlite3.dll", CallingConvention=CallingConvention.Cdecl)] static extern int sqlite3_finalize(IntPtr stmt); static byte[] Utf8(string s) { return Encoding.UTF8.GetBytes(s+"\0"); } static string Text(IntPtr p) { if (p==IntPtr.Zero) return ""; int n=0; while(Marshal.ReadByte(p,n)!=0)n++; byte[] b=new byte[n]; Marshal.Copy(p,b,0,n); return Encoding.UTF8.GetString(b); } public OmegaSqlite(string path, bool readOnly) { int rc=sqlite3_open_v2(Utf8(path),out db,readOnly ? 1 : 6,IntPtr.Zero); if(rc!=0) { string e=Text(sqlite3_errmsg(db)); Dispose(); throw new Exception(e); } } public void Exec(string sql) { IntPtr e; int rc=sqlite3_exec(db,Utf8(sql),IntPtr.Zero,IntPtr.Zero,out e); if(rc!=0) { string msg=Text(e); sqlite3_free(e); throw new Exception(msg); } } public string Scalar(string sql) { IntPtr s; byte[] b=Utf8(sql); if(sqlite3_prepare_v2(db,b,b.Length,out s,IntPtr.Zero)!=0)throw new Exception(Text(sqlite3_errmsg(db))); try { int rc=sqlite3_step(s); if(rc==100)return Text(sqlite3_column_text(s,0)); if(rc==101)return ""; throw new Exception(Text(sqlite3_errmsg(db))); } finally { sqlite3_finalize(s); } } public static int BanlistHash(string[] lines) { uint h=0x7dfcee6a; foreach(string line in lines) { Match m=Regex.Match(line,@"^\s*(\d+)\s+([0-3])(?:\s|$)"); if(!m.Success)continue; uint code=UInt32.Parse(m.Groups[1].Value); int count=Int32.Parse(m.Groups[2].Value); if(code==0)continue; h^=(code<<18)|(code>>14); h^=(code<<(27+count))|(code>>(5-count)); } return unchecked((int)h); } public void Dispose() { if(db!=IntPtr.Zero) { sqlite3_close(db); db=IntPtr.Zero; } } } '@ $db = [OmegaSqlite]::new($database, ($mode -eq 'status')) foreach ($table in @('banlists','bandatas')) { $want = if ($table -eq 'banlists') { 'id,name' } else { 'surrogate,id,flag,flagtype,limits,mode,location' } $cols = $db.Scalar("SELECT group_concat(name,',') FROM (SELECT name FROM pragma_table_info('$table') ORDER BY cid);") if ($cols -ne $want) { throw "Unsupported Omega DB schema: $table ($cols). No changes made." } } $reg = 'Software\Duelists Unite\YGO Omega' $regName = 'LastCurrentBanlist_h353105033' if ($mode -eq 'status') { Write-Host ('Built-in banlists: '+$db.Scalar('SELECT count(*) FROM banlists;')) Write-Host ('Restore data: '+(Test-Path -LiteralPath $stateFile)) $rk = [Microsoft.Win32.Registry]::CurrentUser.OpenSubKey($reg) if ($null -ne $rk) { try { Write-Host ('Default banlist hash: '+$rk.GetValue($regName)) } finally { $rk.Dispose() } } exit 0 } function Sql-Quote([string]$value) { "'"+$value.Replace("'","''")+"'" } function Get-Sha256([string]$path) { $algorithm = [Security.Cryptography.SHA256]::Create() $stream = [IO.File]::OpenRead($path) try { [BitConverter]::ToString($algorithm.ComputeHash($stream)).Replace('-','') } finally { $stream.Dispose(); $algorithm.Dispose() } } function Save-State($state) { $temp = $stateFile+'.tmp' [IO.File]::WriteAllText($temp, ($state | ConvertTo-Json -Depth 6), [Text.UTF8Encoding]::new($false)) Move-Item -LiteralPath $temp -Destination $stateFile -Force } function Restore-CustomLists($state) { foreach ($entry in @($state.hiddenFiles)) { if ([IO.Path]::GetFileName($entry.name) -ne $entry.name -or [IO.Path]::GetFileName($entry.savedName) -ne $entry.savedName) { throw 'Invalid restore filename.' } $dest = Join-Path $lists $entry.name if (Test-Path -LiteralPath $dest) { continue } $source = Join-Path (Join-Path $backup 'hidden-conf') $entry.savedName if ((Get-Sha256 $source) -ne $entry.sha256) { throw 'Custom banlist restore data does not match its recorded hash.' } Copy-Item -LiteralPath $source -Destination $dest if ((Get-Sha256 $dest) -ne $entry.sha256) { throw 'Custom banlist restore verification failed.' } } } if ($mode.StartsWith('apply')) { $text = [IO.File]::ReadAllLines($target) $headers = @($text | Where-Object { $_.StartsWith('!') }) if ($headers.Count -ne 1 -or $headers[0] -ne '!JP2012_09_LIMITED_PRE') { throw 'Expected the installed JP2012_09_LIMITED_PRE list. No changes made.' } $hash = [OmegaSqlite]::BanlistHash($text) New-Item -ItemType Directory -Path $backup -Force | Out-Null if (Test-Path -LiteralPath $stateFile) { $state = Get-Content -LiteralPath $stateFile -Raw | ConvertFrom-Json if ($state.root -ne $root -or $state.version -ne 1) { throw 'Restore data belongs to a different installation or version.' } if ($null -eq $state.PSObject.Properties['active']) { $state | Add-Member -NotePropertyName active -NotePropertyValue ($db.Scalar('SELECT count(*) FROM banlists;') -eq '0') } } else { $state = [pscustomobject]@{ version=1; root=$root; active=$false; registryExists=$false; registryValue=$null; hiddenFiles=@() } } Restore-CustomLists $state if (-not $state.active) { $rk = [Microsoft.Win32.Registry]::CurrentUser.OpenSubKey($reg) $old = $null; $exists = $false if ($null -ne $rk) { try { $exists = $rk.GetValueNames() -contains $regName if ($exists) { if ($rk.GetValueKind($regName) -ne [Microsoft.Win32.RegistryValueKind]::DWord) { throw 'Unexpected default-banlist setting type.' } $old = $rk.GetValue($regName) } } finally { $rk.Dispose() } } $state.registryExists = $exists $state.registryValue = $old Save-State $state } if ($db.Scalar('PRAGMA journal_mode;') -eq 'wal') { throw 'Close other database tools; WAL mode is unsupported for this operation.' } $db.Exec('ATTACH DATABASE '+(Sql-Quote $savedDb)+' AS saved; PRAGMA saved.journal_mode=DELETE; PRAGMA foreign_keys=ON;') try { $db.Exec(@' BEGIN IMMEDIATE; CREATE TABLE IF NOT EXISTS saved.banlists AS SELECT id,name FROM main.banlists WHERE 0; CREATE TABLE IF NOT EXISTS saved.bandatas AS SELECT surrogate,id,flag,flagtype,limits,mode,location FROM main.bandatas WHERE 0; DELETE FROM saved.bandatas WHERE id IN (SELECT id FROM main.banlists); DELETE FROM saved.banlists WHERE id IN (SELECT id FROM main.banlists); INSERT INTO saved.banlists SELECT id,name FROM main.banlists; INSERT INTO saved.bandatas SELECT surrogate,id,flag,flagtype,limits,mode,location FROM main.bandatas; '@) foreach ($table in @('banlists','bandatas')) { $cols = if ($table -eq 'banlists') { 'id,name' } else { 'surrogate,id,flag,flagtype,limits,mode,location' } if ($db.Scalar("SELECT count(*) FROM (SELECT $cols FROM main.$table EXCEPT SELECT $cols FROM saved.$table);") -ne '0') { throw 'Restriction backup verification failed.' } } $db.Exec('DELETE FROM main.bandatas; DELETE FROM main.banlists; COMMIT;') } catch { try { $db.Exec('ROLLBACK;') } catch {}; throw } $rk = [Microsoft.Win32.Registry]::CurrentUser.CreateSubKey($reg) try { $rk.SetValue($regName,$hash,[Microsoft.Win32.RegistryValueKind]::DWord) } finally { $rk.Dispose() } $state.active = $true Save-State $state Write-Host '1209 mode applied. Default: JP2012_09_LIMITED_PRE.' Write-Host 'Built-in lists are hidden. All custom banlists are kept.' Write-Host 'Unlimited is hard-coded by Omega and remains visible.' } else { if (-not (Test-Path -LiteralPath $stateFile) -or -not (Test-Path -LiteralPath $savedDb)) { throw 'No 1209-mode restore data found.' } $state = Get-Content -LiteralPath $stateFile -Raw | ConvertFrom-Json if ($state.root -ne $root -or $state.version -ne 1) { throw 'Restore data belongs to a different installation or version.' } if ($null -eq $state.PSObject.Properties['active']) { $state | Add-Member -NotePropertyName active -NotePropertyValue $true } if ($db.Scalar('PRAGMA journal_mode;') -eq 'wal') { throw 'WAL mode is unsupported for this operation.' } $db.Exec('ATTACH DATABASE '+(Sql-Quote $savedDb)+' AS saved; PRAGMA foreign_keys=ON;') try { $db.Exec(@' BEGIN IMMEDIATE; CREATE TEMP TABLE restore_ids AS SELECT id FROM saved.banlists WHERE id NOT IN (SELECT id FROM main.banlists); DELETE FROM main.bandatas WHERE id IN (SELECT id FROM restore_ids); INSERT INTO main.banlists(id,name) SELECT id,name FROM saved.banlists WHERE id IN (SELECT id FROM restore_ids); INSERT INTO main.bandatas(id,flag,flagtype,limits,mode,location) SELECT id,flag,flagtype,limits,mode,location FROM saved.bandatas WHERE id IN (SELECT id FROM restore_ids); '@) foreach ($table in @('banlists','bandatas')) { $cols = if ($table -eq 'banlists') { 'id,name' } else { 'id,flag,flagtype,limits,mode,location' } if ($db.Scalar("SELECT count(*) FROM (SELECT $cols FROM saved.$table WHERE id IN (SELECT id FROM restore_ids) EXCEPT SELECT $cols FROM main.$table);") -ne '0') { throw 'Restriction restore verification failed.' } } $db.Exec('COMMIT;') } catch { try { $db.Exec('ROLLBACK;') } catch {}; throw } Restore-CustomLists $state if ($state.active) { $rk = [Microsoft.Win32.Registry]::CurrentUser.CreateSubKey($reg) try { if ($state.registryExists) { $rk.SetValue($regName,[int]$state.registryValue,[Microsoft.Win32.RegistryValueKind]::DWord) } else { $rk.DeleteValue($regName,$false) } } finally { $rk.Dispose() } } $state.active = $false Save-State $state Write-Host 'Original banlists and default selection restored. Newer existing lists were preserved.' } $db.Dispose(); $db=$null if ($mode -in @('apply','restore')) { Start-Process -FilePath $exe -WorkingDirectory $root -WindowStyle Normal } } catch { Write-Host ('ERROR: '+$_.Exception.Message) -ForegroundColor Red Write-Host 'Close Omega before changing modes. To restore: Omega_1209.bat restore' exit 1 } finally { if ($null -ne $db) { $db.Dispose() } if ($locked) { $mutex.ReleaseMutex() } $mutex.Dispose() }