~hristoast/wem

ref: 870706716578c50986d8f63eaa7c754c557f6086 wem/env/main.go -rw-r--r-- 20.2 KiB
87070671Hristos N. Triantafillou Allow - in env names, and properly handle names on init 1 year, 26 days ago
                                                                                
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
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
// Package env provides the wine env object.
package env

import (
	"bufio"
	"bytes"
	"errors"
	"fmt"
	"io/ioutil"
	"log"
	"os"
	"os/exec"
	"path/filepath"
	"regexp"
	"strings"
	"text/template"
	"time"

	"git.sr.ht/~hristoast/wem/cfg"
	"git.sr.ht/~hristoast/wem/dll"
	"git.sr.ht/~hristoast/wem/exe"
	"git.sr.ht/~hristoast/wem/opt"
	"github.com/pelletier/go-toml"
)

type Info struct {
	Date string
	Name string
}

type InstallOpts struct {
	GogSilentInstall bool
	InstallArgs      []string
	InstallExe       string
	InstallExpected  string
	InstallWorkDir   string
}

type RunOpts struct {
	QuietRun   bool
	RunArgs    []string
	RunExe     string
	RunPrefix  string
	RunSuffix  string
	RunPre     string
	RunPost    string
	RunWorkDir string
}

type SysOpts struct {
	ReducePulseLatency bool
	RestartPulse       bool
	RestoreResolution  bool
	SingleCore         bool
	SysEnvVars         []string
	VulkanIcdLoader    string
}

type WineOpts struct {
	DxvkVersion      string
	Esync            bool
	Fsync            bool
	VirtualDesktop   string
	Vkd3dVersion     string
	WineArch         string
	WineArgs         []string
	WineDllOverrides string
	WineExe          string
	WinePrefix       string
	WinetricksPath   string
}

type WineEnv struct {
	*Info
	*InstallOpts
	*RunOpts
	*WineOpts
	*SysOpts
}

// AsToml gives a toml representation of the env.
// This represents the configuration file contents.
func (e *WineEnv) AsToml() (string, error) {
	b, err := toml.Marshal(e)
	if err != nil {
		return "", err
	}
	return string(b), nil
}

// CfgExists indicates if the env's configuration file exists.
func (e *WineEnv) CfgExists(name string) bool {
	return dll.IsFile(e.CfgPath(name)) || dll.IsSymlink(e.CfgPath(name))
}

func (e *WineEnv) CfgPath(name string) string {
	return filepath.Join(cfg.CfgDir(), fmt.Sprintf("%s.cfg", name))
}

// HasInstallOpts indicates whether the minimum required config for installation is present
func (e *WineEnv) HasInstallOpts() bool {
	return e.InstallOpts.InstallExe != "" && e.InstallOpts.InstallExpected != ""
}

func (e *WineEnv) InstallString() string {
	// RunPre InstallWorkDir SysEnvVars WineArch WinePrefix WineExe WineArgs InstallExe InstallArgs
	s := &strings.Builder{}

	if e.RunOpts.RunPre != "" {
		s.WriteString(fmt.Sprintf("%s; ", e.RunOpts.RunPre))
	}

	if e.RunOpts.RunWorkDir != "" {
		s.WriteString(fmt.Sprintf("cd %s; ", e.InstallOpts.InstallWorkDir))
	}

	if e.SysOpts.SysEnvVars != nil {
		for _, envVar := range e.SysOpts.SysEnvVars {
			s.WriteString(fmt.Sprintf("%s ", envVar))
		}
	}

	s.WriteString(fmt.Sprintf("WINEARCH=%s ", e.WineOpts.WineArch))
	s.WriteString(fmt.Sprintf("WINEPREFIX=%s ", e.WineOpts.WinePrefix))
	s.WriteString(fmt.Sprintf("%s ", e.WineOpts.WineExe))

	if e.WineOpts.WineArgs != nil {
		for _, wineArg := range e.WineOpts.WineArgs {
			s.WriteString(fmt.Sprintf("%s ", wineArg))
		}
	}

	s.WriteString(fmt.Sprintf("%s ", e.InstallOpts.InstallExe))

	if e.InstallOpts.GogSilentInstall {
		s.WriteString("/dir=c:\\game /verysilent /sp- /suppressmsgboxes ")
	}

	if e.InstallOpts.InstallArgs != nil {
		for _, installArg := range e.InstallOpts.InstallArgs {
			s.WriteString(fmt.Sprintf("%s ", installArg))
		}
	}

	return strings.TrimSuffix(s.String(), " ")
}

func (e *WineEnv) ExeString(exec string, execArgs []string) (string, error) {
	// RunPre RunWorkDir SysEnvVars WineArch WinePrefix Esync Fsync ReducePulseLatency WineDllOverrides/DXVK/VKD3D RunPrefix SingleCore WineExe WineArgs VirtualDesktop RunExe/exec RunArgs RunSuffix RunPost
	s := &strings.Builder{}

	if exec == "" {
		if e.RunOpts.RunPre != "" {
			s.WriteString(fmt.Sprintf("%s; ", e.RunOpts.RunPre))
		}
	}

	if e.RunOpts.RunWorkDir != "" {
		s.WriteString(fmt.Sprintf("cd %s; ", e.RunOpts.RunWorkDir))
	}

	if e.SysOpts.SysEnvVars != nil {
		for _, envVar := range e.SysOpts.SysEnvVars {
			s.WriteString(fmt.Sprintf("%s ", envVar))
		}
	}

	s.WriteString(fmt.Sprintf("WINEARCH=%s ", e.WineOpts.WineArch))
	s.WriteString(fmt.Sprintf("WINEPREFIX=%s ", e.WineOpts.WinePrefix))

	if e.SysOpts.VulkanIcdLoader != "" {
		s.WriteString(fmt.Sprintf("VK_ICD_FILENAMES=%s ", e.SysOpts.VulkanIcdLoader))
	}

	if e.WineOpts.Esync && !e.WineOpts.Fsync {
		s.WriteString("WINEESYNC=1 ")
	}

	if e.WineOpts.Fsync {
		s.WriteString("WINEFSYNC=1 ")
	}

	if e.SysOpts.ReducePulseLatency {
		s.WriteString("PULSE_LATENCY_MSEC=60 ")
	}

	if e.WineOpts.WineDllOverrides != "" || e.WineOpts.DxvkVersion != "" || e.WineOpts.Vkd3dVersion != "" {
		o := &strings.Builder{}
		if e.WineOpts.DxvkVersion != "" {
			o.WriteString("d3d9,d3d10,d3d10core,d3d11=native")
		}
		if e.WineOpts.Vkd3dVersion != "" {
			if o.String() != "" {
				o.WriteString(";")
			}
			o.WriteString("d3d12=native")
		}
		if e.WineOpts.WineDllOverrides != "" {
			if o.String() != "" {
				o.WriteString(";")
			}
			o.WriteString(e.WineOpts.WineDllOverrides)
		}
		s.WriteString(fmt.Sprintf("WINEDLLOVERRIDES=%s ", o.String()))
	}

	if e.RunOpts.RunPrefix != "" {
		s.WriteString(fmt.Sprintf("%s ", e.RunOpts.RunPrefix))
	}

	if e.SysOpts.SingleCore {
		s.WriteString("taskset -c 0 ")
	}

	s.WriteString(fmt.Sprintf("%s ", e.WineOpts.WineExe))

	if e.WineOpts.WineArgs != nil {
		for _, wineArg := range e.WineOpts.WineArgs {
			s.WriteString(fmt.Sprintf("%s ", wineArg))
		}
	}

	if e.WineOpts.VirtualDesktop != "" {
		s.WriteString(fmt.Sprintf("explorer /desktop=%s ", e.WineOpts.VirtualDesktop))
	}

	if exec == "" {
		s.WriteString(strings.ReplaceAll(e.RunOpts.RunExe, "\\", "\\\\"))

		if e.RunOpts.RunArgs != nil {
			for _, runArg := range e.RunOpts.RunArgs {
				s.WriteString(fmt.Sprintf(" %s", runArg))
			}
		}

		if e.RunOpts.RunSuffix != "" {
			s.WriteString(fmt.Sprintf(" %s", e.RunOpts.RunSuffix))
		}

		if e.RunOpts.RunPost != "" {
			s.WriteString(fmt.Sprintf("; %s", e.RunOpts.RunPost))
		}
	} else {
		execRendered, err := e.RenderString(exec)
		if err != nil {
			return "", err
		}
		s.WriteString(execRendered)
		for _, arg := range execArgs {
			s.WriteString(" ")
			s.WriteString(arg)
		}
	}

	return s.String(), nil
}

func (e *WineEnv) PrefixExists() bool {
	stat, err := os.Stat(e.WineOpts.WinePrefix)
	if err != nil {
		return false
	}
	return stat.IsDir() || dll.IsSymlink(e.WineOpts.WinePrefix)
}

func (e *WineEnv) ctx() (*exe.ExeCtx, error) {
	ctx := &exe.ExeCtx{
		Args:    []string{},
		Command: e.WineOpts.WineExe,
		EnvName: e.Info.Name,
		EnvVars: e.SysOpts.SysEnvVars,
		Prefix:  e.RunOpts.RunPrefix,
		Stderr:  os.Stderr,
		Stdout:  os.Stdout,
		Suffix:  e.RunOpts.RunSuffix,
		Title:   "",
		WorkDir: e.RunOpts.RunWorkDir,
	}

	wineVars := []string{
		fmt.Sprintf("WINEARCH=%s", e.WineOpts.WineArch),
		fmt.Sprintf("WINEPREFIX=%s", e.WineOpts.WinePrefix),
	}
	ctx.EnvVars = append(ctx.EnvVars, wineVars...)

	if e.RunOpts.QuietRun {
		devnull, err := os.Open(os.DevNull)
		if err != nil {
			return nil, err
		}
		ctx.Stderr = devnull
		ctx.Stdout = devnull
	}

	return ctx, nil
}

func (e *WineEnv) RunCtx(cacheDir string) (*exe.ExeCtx, error) {
	ctx, err := e.ctx()
	if err != nil {
		return nil, err
	}
	if e.WineOpts.VirtualDesktop != "" {
		log.Printf("Enable Virtual Desktop (%s)", e.WineOpts.VirtualDesktop)
		ctx.Args = append(
			ctx.Args,
			"explorer",
			fmt.Sprintf("/desktop=%s", e.WineOpts.VirtualDesktop),
		)
	}
	ctx.Args = append(ctx.Args, e.RunOpts.RunExe)
	ctx.Args = append(ctx.Args, e.RunOpts.RunArgs...)
	ctx.Title = fmt.Sprintf("Run \"%s\" (%s)", e.Info.Name, e.Info.Date)

	// VulkanIcdLoader
	if e.SysOpts.VulkanIcdLoader != "" {
		log.Println("Set VulkanIcdLoader")
		ctx.EnvVars = append(ctx.EnvVars, fmt.Sprintf("VK_ICD_FILENAMES=%s", e.SysOpts.VulkanIcdLoader))
	}

	// ESYNC
	if e.WineOpts.Esync && !e.WineOpts.Fsync {
		can, err := e.wineCan("esync")
		if err != nil {
			return nil, err
		}

		log.Println("Enable ESYNC")
		if !can {
			log.Println("WARNING: your wine build may not support esync!")
		}
		ctx.EnvVars = append(ctx.EnvVars, "WINEESYNC=1")
	}

	if e.WineOpts.Esync && e.WineOpts.Fsync {
		log.Println("WARNING: Esync has been disabled since fsync is also enabled.")
	}

	// FSYNC
	if e.WineOpts.Fsync {
		can, err := e.wineCan("fsync")
		if err != nil {
			return nil, err
		}

		log.Println("Enable FSYNC")
		if !can {
			log.Println("WARNING: Your wine build may not support fsync!")
		}
		ctx.EnvVars = append(ctx.EnvVars, "WINEFSYNC=1")
	}

	// Reduce Pulse Latency
	if e.SysOpts.ReducePulseLatency {
		log.Println("Reduce PulseAudio latency")
		ctx.EnvVars = append(ctx.EnvVars, "PULSE_LATENCY_MSEC=60")
	}

	//Restart Pulse
	if e.SysOpts.RestartPulse {
		log.Println("Restart PulseAudio")
		// Discard output; we don't care. Only that it worked or not.
		_, err := exe.QuickExe("pulseaudio", "--kill")
		if err != nil {
			return nil, err
		}
		time.Sleep(1 * time.Second)
		_, err = exe.QuickExe("pulseaudio", "--start")
		if err != nil {
			return nil, err
		}
	}

	// Restore Resolution: Save
	if e.SysOpts.RestoreResolution {
		log.Println("Save Resolution")
		xrandr, err := opt.ExePath("xrandr")
		if err != nil {
			return nil, err
		}
		displays, err := opt.DisplayResolutions(xrandr)
		if err != nil {
			return nil, err
		}
		ctx.Displays = displays
	}

	// Single Core
	if e.SysOpts.SingleCore {
		log.Println("Single Core")
		oldCmnd := ctx.Command
		oldArgs := ctx.Args
		ctx.Command = "taskset"
		ctx.Args = []string{"-c", "0", oldCmnd}
		ctx.Args = append(ctx.Args, oldArgs...)
	}

	var overrides string
	// Wine DLL overrides; do user overrides before any required ones
	if e.WineOpts.WineDllOverrides != "" {
		log.Println("Wine DLL Overrides")
		overrides = e.WineOpts.WineDllOverrides
	}

	// Ensure the wine prefix dir exists before doing DXVK or VKD3D
	if !e.PrefixExists() && (e.WineOpts.DxvkVersion != "" || e.WineOpts.Vkd3dVersion != "") {
		log.Println("Generate Wine Prefix")
		err = exe.GenPrefix(e.WineOpts.WineExe, e.WineOpts.WinePrefix, e.WineOpts.WineArch)
		if err != nil {
			return nil, err
		}
	}

	has64 := e.WineOpts.WineArch == "win64" && e.wineCan64()
	// DXVK
	if e.WineOpts.DxvkVersion != "" {
		log.Printf("Enable DXVK v%s", e.WineOpts.DxvkVersion)

		// Is it a valid version?
		valid, offline := e.ValidDllVersion(cacheDir, dll.DxvkKind, dll.DxvkReleaseURL, e.WineOpts.DxvkVersion)
		if valid || offline {
			// Enable the DXVK DLLs
			err = dll.EnableAll(has64, cacheDir, dll.DxvkKind, e.WineOpts.WineArch, e.WineOpts.WinePrefix, e.WineOpts.DxvkVersion)
			if err != nil {
				return nil, err
			}

			// Inject DLL overrides
			if overrides != "" {
				overrides += ";"
			}
			overrides += "d3d9,d3d10,d3d10core,d3d11=native"

		} else {
			return nil, fmt.Errorf("invalid DXVK version: %s", e.WineOpts.DxvkVersion)
		}

	} else if !strings.Contains(e.WineOpts.WineExe, "Proton-") {
		// Disable the DXVK DLLs
		err = dll.DisableAll(has64, cacheDir, dll.DxvkKind, e.WineOpts.WineArch, e.WineOpts.WinePrefix, e.WineOpts.DxvkVersion)
		if err != nil {
			return nil, err
		}
	}

	// VKD3D
	if e.WineOpts.Vkd3dVersion != "" {
		log.Printf("Enable VKD3D v%s", e.WineOpts.Vkd3dVersion)

		// Is it a valid version?
		valid, offline := e.ValidDllVersion(cacheDir, dll.Vkd3dKind, dll.Vkd3dReleaseURL, e.WineOpts.Vkd3dVersion)
		if valid || offline {
			// Enable the VKD3D DLLs
			err = dll.EnableAll(has64, cacheDir, dll.Vkd3dKind, e.WineOpts.WineArch, e.WineOpts.WinePrefix, e.WineOpts.Vkd3dVersion)
			if err != nil {
				return nil, err
			}

			// Inject DLL overrides
			if overrides != "" {
				overrides += ";"
			}
			overrides += "d3d12=native"

		} else {
			return nil, fmt.Errorf("invalid VKD3D version: %s", e.WineOpts.Vkd3dVersion)
		}

	} else if !strings.Contains(e.WineOpts.WineExe, "Proton-") {
		// Disable the VKD3D DLLs
		err = dll.DisableAll(has64, cacheDir, dll.Vkd3dKind, e.WineOpts.WineArch, e.WineOpts.WinePrefix, e.WineOpts.Vkd3dVersion)
		if err != nil {
			return nil, err
		}

	}

	// Actually apply any overrides
	if overrides != "" {
		ctx.EnvVars = append(ctx.EnvVars, fmt.Sprintf("WINEDLLOVERRIDES=%s", overrides))
	}

	return ctx, nil
}

func (e *WineEnv) PreRunCtx() (*exe.ExeCtx, error) {
	if e.RunOpts.RunPre != "" {
		ctx, err := e.ctx()
		if err != nil {
			return nil, err
		}
		runPre := strings.Split(e.RunOpts.RunPre, " ")
		ctx.Command = runPre[0]
		ctx.Args = append(ctx.Args, runPre[1:]...)
		ctx.EnvVars = append(ctx.EnvVars, fmt.Sprintf("WINE=%s", e.WineOpts.WineExe))
		ctx.Title = "PreRun"
		return ctx, nil
	}
	return nil, nil
}

func (e *WineEnv) PostRunCtx() (*exe.ExeCtx, error) {
	if e.RunOpts.RunPost != "" {
		ctx, err := e.ctx()
		if err != nil {
			return nil, err
		}
		runPost := strings.Split(e.RunOpts.RunPost, " ")
		ctx.Command = runPost[0]
		ctx.Args = append(ctx.Args, runPost[1:]...)
		ctx.EnvVars = append(ctx.EnvVars, fmt.Sprintf("WINE=%s", e.WineOpts.WineExe))
		ctx.Title = "PostRun"
		return ctx, nil
	}
	return nil, nil
}

func (e *WineEnv) InstallCtx() (*exe.ExeCtx, error) {
	ctx, err := e.ctx()
	if err != nil {
		return nil, err
	}
	ctx.WorkDir = e.InstallOpts.InstallWorkDir
	ctx.Args = append(ctx.Args, e.InstallOpts.InstallExe)
	ctx.Args = append(ctx.Args, e.InstallOpts.InstallArgs...)
	if e.InstallOpts.GogSilentInstall {
		ctx.Args = append(ctx.Args, []string{"/dir=c:\\game", "/verysilent", "/sp-", "/suppressmsgboxes"}...)
	}
	ctx.Title = fmt.Sprintf("Install \"%s\" (%s)", e.Info.Name, e.Info.Date)
	return ctx, nil
}

func (e *WineEnv) ExeCtx(cacheDir string, skipInstall, skipRun bool) ([]*exe.ExeCtx, error) {
	var err error
	var installCtx *exe.ExeCtx
	var runCtx *exe.ExeCtx

	if !skipInstall && e.ShouldInstall() {
		installCtx, err = e.InstallCtx()
		if err != nil {
			return nil, err
		}
	}

	preCtx, err := e.PreRunCtx()
	if err != nil {
		return nil, err
	}

	if !skipRun {
		runCtx, err = e.RunCtx(cacheDir)
		if err != nil {
			return nil, err
		}
	}

	postCtx, err := e.PostRunCtx()
	if err != nil {
		return nil, err
	}

	return []*exe.ExeCtx{installCtx, preCtx, runCtx, postCtx}, nil
}

func (e *WineEnv) ExpectedExists() bool {
	return dll.IsFile(e.InstallOpts.InstallExpected) || dll.IsSymlink(e.InstallOpts.InstallExpected)
}

func (e *WineEnv) IsInstalled() bool {
	if e.InstallOpts.InstallExe != "" && e.RunOpts.RunExe == "" {
		return false
	}
	return e.ExpectedExists()
}

// RenderString is for when you need to one-off render a string.
func (e *WineEnv) RenderString(s string) (string, error) {
	tpl, err := template.New("rendered").Parse(s)
	if err != nil {
		return "", err
	}

	buf := new(bytes.Buffer)
	err = tpl.Execute(buf, e)
	if err != nil {
		return "", err
	}

	return buf.String(), nil
}

// Save writes the WineEnv to disk as a toml-formatted cfg file.
func (e *WineEnv) Save(name string) error {
	t, err := e.AsToml()
	if err != nil {
		return err
	}

	c := e.CfgPath(name)
	f, err := os.Create(c)
	if err != nil {
		return err
	}

	w := bufio.NewWriter(f)
	defer w.Flush()
	for _, l := range strings.Split(t, "\n") {
		_, err := w.WriteString(l + "\n")
		if err != nil {
			return err
		}
	}

	return nil
}

func (e *WineEnv) SetDefaults(c *cfg.WemConfig) error {

	slug, err := e.Slug()
	if err != nil {
		return err
	}

	if e.WineOpts.WineExe == "" {
		wineExe, err := opt.ExePath("wine")
		if err != nil {
			return errors.New("a wine executable was not found; please ensure wine and winetricks are installed before using WEM")
		}
		e.WineOpts.WineExe = wineExe
	}

	if e.Info.Date == "" {
		e.Info.Date = time.Now().Format("2006-01-02 15:04:05")
	}

	if e.WineOpts.WineArch == "" {
		e.WineOpts.WineArch = "win64"
	}

	if e.WineOpts.WinePrefix == "" {
		e.WineOpts.WinePrefix = filepath.Join(c.WineEnvDir, slug)
	}

	winetricks, err := opt.ExePath("winetricks")
	if err != nil {
		winetricks = ""
	}

	if e.WineOpts.WinetricksPath == "" {
		e.WineOpts.WinetricksPath = winetricks
	}

	return nil
}

func (e *WineEnv) ShouldInstall() bool {
	return e.HasInstallOpts() && !e.IsInstalled()
}

// Slug is a safe version of the env Name, consisting only of alphanumerics.
func (e *WineEnv) Slug() (string, error) {
	slug, err := Slugify(e.Info.Name)
	if err != nil {
		return "", err
	}
	return slug, nil
}

func Slugify(name string) (string, error) {
	reg, err := regexp.Compile(`[^a-zA-Z0-9\-]+`)
	if err != nil {
		return "", err
	}
	return reg.ReplaceAllString(name, ""), nil
}

func (e *WineEnv) ValidDllVersion(cacheDir, kind, url, version string) (bool, bool) {
	ov := e.offlineValidate(cacheDir, kind, version)
	if ov {
		return false, true
	}

	// Request a list of versions from the API, check against those
	vers, err := opt.GetVersions(url)
	if err != nil {
		if strings.Contains(err.Error(), "API rate limit") {
			log.Printf("%s validation: "+err.Error(), strings.ToUpper(kind))
			// Return true here because there's no way to actually validate it.
			// We don't want to block on being ratelimited..
			return true, false

		} else {
			log.Printf("There was an error getting available %s versions!", strings.ToUpper(kind))
			return false, false
		}
	}

	for _, v := range vers {
		if v == version || v == "v"+version {
			return true, false
		}
	}
	return false, false
}

func (e *WineEnv) offlineValidate(cacheDir, filePrefix, version string) bool {
	// First check that the requested version is already installed by one name or another
	_, err := os.Stat(filepath.Join(cacheDir, fmt.Sprintf("%s-%s", filePrefix, version)))
	if err == nil {
		return true
	}
	_, err = os.Stat(filepath.Join(cacheDir, e.WineOpts.Vkd3dVersion))
	return err == nil
}

// Validate ensures that mandatory config values are set.
func (e *WineEnv) Validate() error {
	var missing string

	if e.RunOpts.RunExe == "" && e.InstallOpts.InstallExe == "" {
		missing += "RunExe "
	}

	if e.WineOpts.WineArch == "" {
		missing += "WineArch "
	}

	if e.WineOpts.WineExe == "" {
		missing += "WineExe "
	}

	if e.WineOpts.WinePrefix == "" {
		missing += "WinePrefix "
	}

	if e.WineOpts.WineArch == "win64" && !e.wineCan64() {
		log.Println("WARNING: A 64-bit prefix has been selected, but no 64-bit wine is available!")
		log.Println("WARNING: WEM is auto-adjusting the prefix to 32-bit, please update")
		log.Println("WARNING: your config or make a 64-bit wine available on your system")
		e.WineOpts.WineArch = "win32"
	}

	if missing != "" {
		return fmt.Errorf("missing required config options: %s", missing)
	}

	return nil
}

func (e *WineEnv) wineCan(cap string) (bool, error) {
	c := exec.Command(e.WineOpts.WineExe, "--version")
	o, err := c.CombinedOutput()
	if err != nil {
		return false, err
	}

	output := strings.ToLower(string(o))
	if strings.Contains(output, cap) {
		return true, nil
	}

	if strings.Contains(output, "staging") {
		return true, nil
	}

	// A very wild guess but... actual proton doesn't report in a meaningful way.
	if strings.Contains(strings.ToLower(e.WineOpts.WineExe), "proton") {
		return true, nil
	}

	return false, nil
}

func (e *WineEnv) wineCan64() bool {
	path, err := opt.ExePath("wine64")
	if err != nil {
		return false
	}
	if path == "" {
		return false
	}
	return true
}

func FromName(name string, render bool) (*WineEnv, error) {
	s, err := Slugify(name)
	if err != nil {
		return nil, err
	}

	p := filepath.Join(os.Getenv("HOME"), ".config", "wem", fmt.Sprintf("%s.cfg", s))
	env, err := fromPath(p, render)
	if err != nil {
		return nil, err
	}

	return env, nil
}

// Take a string that's a file path and read it like it's an env cfg file.
func fromPath(p string, render bool) (*WineEnv, error) {
	e, err := ioutil.ReadFile(p)
	if err != nil {
		return nil, err
	}

	info := &Info{}
	installOpts := &InstallOpts{}
	runOpts := &RunOpts{}
	wineOpts := &WineOpts{}
	sysOpts := &SysOpts{}

	toml.Unmarshal(e, info)
	toml.Unmarshal(e, installOpts)
	toml.Unmarshal(e, runOpts)
	toml.Unmarshal(e, wineOpts)
	toml.Unmarshal(e, sysOpts)

	we := &WineEnv{
		Info:        info,
		InstallOpts: installOpts,
		RunOpts:     runOpts,
		WineOpts:    wineOpts,
		SysOpts:     sysOpts,
	}

	if render {
		b, err := renderCfg(e, we)
		if err != nil {
			return nil, err
		}
		info := &Info{}
		installOpts := &InstallOpts{}
		runOpts := &RunOpts{}
		wineOpts := &WineOpts{}
		sysOpts := &SysOpts{}

		toml.Unmarshal(b, info)
		toml.Unmarshal(b, installOpts)
		toml.Unmarshal(b, runOpts)
		toml.Unmarshal(b, wineOpts)
		toml.Unmarshal(b, sysOpts)

		we = &WineEnv{
			Info:        info,
			InstallOpts: installOpts,
			RunOpts:     runOpts,
			WineOpts:    wineOpts,
			SysOpts:     sysOpts,
		}
	}

	return we, nil
}

func renderCfg(tomlCfg []byte, e *WineEnv) ([]byte, error) {
	tomlStr := os.ExpandEnv(string(tomlCfg))
	tpl, err := template.New("rendered").Parse(tomlStr)
	if err != nil {
		return nil, err
	}

	buf := new(bytes.Buffer)
	err = tpl.Execute(buf, e)
	if err != nil {
		return nil, err
	}

	return buf.Bytes(), nil
}