-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
245 lines (191 loc) · 6.82 KB
/
main.go
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
235
236
237
238
239
240
241
242
243
244
245
package main
import (
"context"
"flag"
"fmt"
"log"
"os"
"path"
"time"
"github.com/mpawlowski/r2modman-headless/r2modman"
"github.com/mpawlowski/r2modman-headless/zip"
"go.uber.org/fx"
)
type flags struct {
installDir string
profileZip string
runTimeout time.Duration
thunderstoreCDNHost string
thunderstoreCdnTimeout time.Duration
thunderstoreForceDownload bool
thunderstoreMetadataURL string
thunderstoreMetadataTimeout time.Duration
version bool
workDir string
}
var Usage = func() {
fmt.Fprintf(os.Stderr, "%s - Apply a profile export from r2modman to a dedicated server.\n", os.Args[0])
fmt.Fprintf(os.Stderr, "Example:\n\t%s --install-dir=serverfiles/ --work-dir=work/ --profile-zip=Profile.r2z\n", os.Args[0])
fmt.Fprintf(os.Stderr, "Flags:\n")
flag.PrintDefaults()
}
var options flags
func init() {
flag.Usage = Usage
options = flags{}
flag.DurationVar(&options.runTimeout, "run-timeout", 5*time.Minute, "Total maximum runtime before giving up.")
flag.StringVar(&options.profileZip, "profile-zip", "", "Profile export to apply.")
flag.StringVar(&options.installDir, "install-dir", "", "Installation directory of the server.")
flag.BoolVar(&options.thunderstoreForceDownload, "thunderstore-force-download", false, "Force re-download of all mods, even if they are already present in the work directory.")
flag.StringVar(&options.thunderstoreCDNHost, "thunderstore-cdn-host", "gcdn.thunderstore.io", "Hostname of the thunderstore CDN to use.")
flag.DurationVar(&options.thunderstoreCdnTimeout, "thunderstore-cdn-timeout", 30*time.Second, "Timeout while downloading each mod.")
flag.StringVar(&options.thunderstoreMetadataURL, "thunderstore-metadata-url", "https://thunderstore.io/c/valheim/api/v1/package/", "URL to the thunderstore metadata API. This can vary between games.")
flag.DurationVar(&options.thunderstoreMetadataTimeout, "thunderstore-metadata-timeout", 10*time.Second, "Timeout while downloading the thunderstore mod metadata.")
flag.BoolVar(&options.version, "version", false, "Print version and exit.")
flag.StringVar(&options.workDir, "work-dir", "tmp/", "Temporary work directory for downloaded files.")
flag.Parse()
if options.version {
info := GetBuildInfo()
fmt.Println(info.toJson())
os.Exit(0)
}
if options.installDir == "" {
log.Fatal("--install-dir must be defined")
}
if options.profileZip == "" {
log.Fatal("--profile-zip must be defined")
}
if _, err := os.Stat(options.installDir); os.IsNotExist(err) {
log.Fatal("provided --install-dir does not exist: " + options.installDir)
}
if _, err := os.Stat(options.profileZip); os.IsNotExist(err) {
log.Fatal("provided --profile-zip does not exist: " + options.profileZip)
}
if _, err := os.Stat(options.workDir); os.IsNotExist(err) {
log.Fatal("provided --work-dir does not exist: " + options.workDir)
}
//normalize directories
options.installDir = path.Clean(options.installDir)
options.workDir = path.Clean(options.workDir)
}
func main() {
info := GetBuildInfo()
fmt.Println(info.toJson())
var fxOptions []fx.Option
fxOptions = append(fxOptions,
r2modman.Module(r2modman.Config{
InstallDirectory: options.installDir,
WorkDirectory: options.workDir,
ThunderstoreCDNTimeout: options.thunderstoreCdnTimeout,
ThunderstoreCDN: options.thunderstoreCDNHost,
ThunderstoreForceDownload: options.thunderstoreForceDownload,
}),
zip.Module(zip.Config{}),
fx.Invoke(registerLifecycleHooks),
)
app := fx.New(fxOptions...)
// start
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
err := app.Start(ctx)
if err != nil {
panic(err)
}
// wait for app to finish
signal := <-app.Wait()
// stop
stopCtx, stopCancel := context.WithTimeout(context.Background(), 5*time.Second)
defer stopCancel()
err = app.Stop(stopCtx)
if err != nil {
panic(err)
}
//exit with signal
os.Exit(signal.ExitCode)
}
func run(
ctx context.Context,
parser r2modman.ExportParser,
modutil r2modman.ModUtil,
extractor zip.Extractor,
) error {
log.Println("Using profile", options.profileZip)
metadata, err := parser.Parse(options.profileZip)
if err != nil {
return err
}
metadataCtx, metadataCtxCancel := context.WithTimeout(ctx, options.thunderstoreMetadataTimeout)
defer metadataCtxCancel()
packages, err := r2modman.GetPackagesMetadata(metadataCtx, options.thunderstoreMetadataURL)
if err != nil {
log.Printf("unable to pull thunderstore api: %s", err)
return err
}
log.Printf("Found packages %d packages from thunderstore\n", len(packages))
for _, v := range metadata.Mods {
log.Printf("processing %s\n", v.Name)
downloadedZipPath := path.Join(options.workDir, v.Filename())
thunderstoreMeta, ok := packages[v.ThunderstoreKey()]
if !ok {
return fmt.Errorf("thunderstore metadata does not exist for: %s", v.ThunderstoreKey())
}
err = modutil.Download(v, thunderstoreMeta)
if err != nil {
return err
}
//extract modes to install directory
packagingType, prefixToStrip, err := r2modman.DeterminePackagingType(downloadedZipPath)
if err != nil {
return err
}
installDir := fmt.Sprintf("%s/%s", options.installDir, packagingType.Directory())
if packagingType == r2modman.ModPackagingTypePlugin {
installDir += fmt.Sprintf("/plugins/%s", v.Name)
}
if packagingType == r2modman.ModPackagingTypeRootDLL {
installDir += fmt.Sprintf("/%s", v.Name)
}
log.Printf("Packaging Type: %s", packagingType)
log.Printf("Install Dir: %s", installDir)
log.Printf("Prefix Strip: %s", prefixToStrip)
err = extractor.Extract(downloadedZipPath, installDir, prefixToStrip)
if err != nil {
return err
}
log.Printf("")
}
// extract profile to bepinex in install dir
bepinDir := path.Join(options.installDir, "/BepInEx")
err = extractor.Extract(options.profileZip, bepinDir, "BepInEx")
if err != nil {
return err
}
log.Printf("Mod install finished successfully, configure your start script at %s/start_server_bepinex.sh\n", options.installDir)
return nil
}
func registerLifecycleHooks(
lc fx.Lifecycle,
shutdowner fx.Shutdowner,
parser r2modman.ExportParser,
modutil r2modman.ModUtil,
extractor zip.Extractor,
) {
lc.Append(fx.Hook{OnStart: func(c context.Context) error {
errorChannel := make(chan error)
go func(returnChannel chan<- error) {
myCtx, myCtxCancel := context.WithTimeout(context.Background(), options.runTimeout)
defer myCtxCancel()
returnChannel <- run(myCtx, parser, modutil, extractor)
}(errorChannel)
go func(errChan chan error, shutdowner fx.Shutdowner) {
err := <-errChan
if err != nil {
log.Printf("Error processing mods: %v", err)
shutdowner.Shutdown(fx.ExitCode(1))
return
}
shutdowner.Shutdown(fx.ExitCode(0))
}(errorChannel, shutdowner)
return nil
}})
}