-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathProgram.cs
234 lines (205 loc) · 9.93 KB
/
Program.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
/*
* Copyright 2009-2014 Matvei Stefarov <[email protected]>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*/
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.IO.Compression;
using System.Reflection;
using System.Threading;
using System.Linq;
using System.Xml.Linq;
using fCraft.UpdateInstaller.Properties;
namespace fCraft.UpdateInstaller {
static class Program {
const string ConfigFileNameDefault = "config.xml",
BackupFileNameFormat = "fCraftData_{0:yyyyMMdd'_'HH'-'mm'-'ss}_BeforeUpdate.zip";
public const string DataBackupDirectory = "databackups";
static readonly string[] FilesToBackup = new[]{
"PlayerDB.txt",
"config.xml",
"ipbans.txt",
"worlds.xml"
};
static readonly string[] LegacyFiles = new[]{
"fCraftConsole.exe",
"fCraftUI.exe",
"ConfigTool.exe",
"fCraftWinService.exe"
};
static int Main( string[] args ) {
string restartTarget = null;
string configFileName = ConfigFileNameDefault;
// Set path
string defaultPath = Path.GetFullPath( Path.GetDirectoryName( Assembly.GetExecutingAssembly().Location ) );
Directory.SetCurrentDirectory( defaultPath );
// Parse command-line arguments
List<string> argsList = new List<string>();
foreach( string arg in args ) {
Console.WriteLine( arg );
if( arg.StartsWith( "--path=", StringComparison.OrdinalIgnoreCase ) ) {
Directory.SetCurrentDirectory( arg.Substring( arg.IndexOf( '=' ) + 1 ).TrimQuotes() );
argsList.Add( arg );
} else if( arg.StartsWith( "--config=", StringComparison.OrdinalIgnoreCase ) ) {
configFileName = arg.Substring( arg.IndexOf( '=' ) + 1 ).TrimQuotes();
argsList.Add( arg );
} else if( arg.StartsWith( "--restart=", StringComparison.OrdinalIgnoreCase ) ) {
restartTarget = arg.Substring( arg.IndexOf( '=' ) + 1 ).TrimQuotes();
} else if( arg != "&" ) {
argsList.Add( arg );
}
}
// Parse update settings
string runBefore = null,
runAfter = null;
bool doBackup = true;
try {
if( File.Exists( configFileName ) ) {
XDocument doc = XDocument.Load( configFileName );
if( doc.Root != null ) {
XElement elRunBefore = doc.Root.Element( "RunBeforeUpdate" );
if( elRunBefore != null ) runBefore = elRunBefore.Value;
XElement elRunAfter = doc.Root.Element( "RunAfterUpdate" );
if( elRunAfter != null ) runAfter = elRunAfter.Value;
XElement elDoBackup = doc.Root.Element( "BackupBeforeUpdate" );
if( elDoBackup != null && !String.IsNullOrEmpty( elDoBackup.Value ) ) {
if( !Boolean.TryParse( elDoBackup.Value, out doBackup ) ) {
doBackup = true;
}
}
}
}
} catch( Exception ex ) {
Console.Error.WriteLine( "Error reading fCraft config: {0}", ex );
}
// Backup data files (if requested)
if( doBackup ) DoBackup();
// Run pre-update script (if any)
if( !String.IsNullOrEmpty( runBefore ) ) {
Console.WriteLine( "Executing pre-update script..." );
try {
Process preUpdateProcess = Process.Start( runBefore, "" );
if( preUpdateProcess != null ) preUpdateProcess.WaitForExit();
} catch( Exception ex ) {
Console.Error.WriteLine( "Failed to run pre-update process, aborting update application: {0}", ex );
return (int)ReturnCodes.FailedToRunPreUpdateCommand;
}
}
// Apply the update
using( MemoryStream ms = new MemoryStream( Resources.Payload ) ) {
using( ZipStorer zs = ZipStorer.Open( ms, FileAccess.Read ) ) {
var allFiles = zs.ReadCentralDir().Select( entry => entry.FileNameInZip ).Union( LegacyFiles );
// ensure that fcraft files are writable
bool allPassed;
do {
allPassed = true;
foreach( var fileName in allFiles ) {
try {
FileInfo fi = new FileInfo( fileName );
if( !fi.Exists ) continue;
using( fi.OpenWrite() ) { }
} catch( Exception ex ) {
if( ex is IOException ) {
Console.WriteLine( "Waiting for fCraft-related applications to close..." );
} else {
Console.Error.WriteLine( "ERROR: could not write to {0}: {1} - {2}",
fileName, ex.GetType().Name, ex.Message );
Console.WriteLine();
}
allPassed = false;
Thread.Sleep( 1000 );
break;
}
}
} while( !allPassed );
// delete legacy files
foreach( var legacyFile in LegacyFiles ) {
try {
File.Delete( legacyFile );
} catch( Exception ex ) {
Console.Error.WriteLine( " ERROR: {0} {1}", ex.GetType().Name, ex.Message );
}
}
// extract files
foreach( var entry in zs.ReadCentralDir() ) {
Console.WriteLine( "Extracting {0}", entry.FileNameInZip );
try {
using( FileStream fs = File.Create( entry.FileNameInZip ) ) {
zs.ExtractFile( entry, fs );
}
} catch( Exception ex ) {
Console.Error.WriteLine( " ERROR: {0} {1}", ex.GetType().Name, ex.Message );
}
}
}
}
// Run post-update script
if( !String.IsNullOrEmpty( runAfter ) ) {
Console.WriteLine( "Executing post-update script..." );
try {
Process postUpdateProcess = Process.Start( runAfter, "" );
if( postUpdateProcess != null ) postUpdateProcess.WaitForExit();
} catch( Exception ex ) {
Console.Error.WriteLine( "Failed to run post-update process, aborting restart: {0}", ex );
return (int)ReturnCodes.FailedToRunPostUpdateCommand;
}
}
Console.WriteLine( "fCraft update complete." );
// Restart fCraft (if requested)
if( restartTarget != null ) {
string argString = String.Join( " ", argsList.ToArray() );
Console.WriteLine( "Starting: {0} {1}", restartTarget, argString );
Process.Start( restartTarget, argString );
}
return (int)ReturnCodes.Ok;
}
static void DoBackup() {
if( !Directory.Exists( DataBackupDirectory ) ) {
Directory.CreateDirectory( DataBackupDirectory );
}
string backupFileName = String.Format( BackupFileNameFormat, DateTime.Now ); // localized
backupFileName = Path.Combine( DataBackupDirectory, backupFileName );
using( FileStream fs = File.Create( backupFileName ) ) {
using( ZipStorer backupZip = ZipStorer.Create( fs, "" ) ) {
foreach( string dataFileName in FilesToBackup ) {
if( File.Exists( dataFileName ) ) {
backupZip.AddFile( ZipStorer.Compression.Deflate, dataFileName, dataFileName, "" );
}
}
}
}
}
static string TrimQuotes( this string str ) {
if( str.StartsWith( "\"" ) && str.EndsWith( "\"" ) ) {
return str.Substring( 1, str.Length - 2 );
} else {
return str;
}
}
}
enum ReturnCodes {
Ok = 0,
FailedToRunPreUpdateCommand = 1,
FailedToRunPostUpdateCommand = 2
}
}