aboutsummarylogtreecommitdiffstats
path: root/wegame-dwproton
blob: 6ac77a0eb5dc95a1e749603065dc22705a88923d (plain)
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
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
#!/usr/bin/bash
# SPDX-FileCopyrightText: 2026 ParticleG
# SPDX-License-Identifier: 0BSD
# shellcheck disable=SC2218 # ShellCheck 0.11 misorders calls to functions defined above.

set -euo pipefail

readonly APP_ID='wegame-dwproton'
readonly PACKAGE_VERSION='7.06.27.1446'
readonly STEAM_APP_ID='3493550319'

share_dir="${WEGAME_DWPROTON_SHARE_DIR:-/usr/share/${APP_ID}}"
proton="${WEGAME_DWPROTON_PROTON:-}"
data_home="${XDG_DATA_HOME:-$HOME/.local/share}"
state_home="${XDG_STATE_HOME:-$HOME/.local/state}"
cache_home="${XDG_CACHE_HOME:-$HOME/.cache}"

readonly data_dir="$data_home/$APP_ID"
readonly state_dir="$state_home/$APP_ID"
readonly cache_dir="$cache_home/$APP_ID"
readonly compat_data="$data_dir/compatdata"
readonly prefix="$compat_data/pfx"
readonly steam_root="$data_dir/steam"
readonly installer="$share_dir/WeGameMiniLoader.exe"
readonly nested_x11_fix="$share_dir/wegame-nested-x11-fix"
readonly twm_config="$share_dir/wegame-twmrc"
readonly install_dir="$prefix/drive_c/Program Files (x86)/WeGame"
readonly client="$install_dir/wegame.exe"
readonly update_status="$install_dir/update.tmp"
readonly update_payload="$install_dir/wegame_update"
readonly backup_root="$state_dir/update-backups"
readonly lock_file="$state_dir/launcher.lock"
readonly prefix_config_marker="$prefix/.wegame-dwproton-config-v1"
update_recovered=0
update_managed_pending=0

log() {
    printf '%s: %s\n' "$APP_ID" "$*"
}

notify_error() {
    if [[ ! -t 2 ]] && command -v notify-send >/dev/null 2>&1; then
        notify-send --urgency=critical 'WeGame (DWProton)' "$1" >/dev/null 2>&1 || true
    fi
}

die() {
    printf '%s: error: %s\n' "$APP_ID" "$*" >&2
    notify_error "$*"
    exit 1
}

usage() {
    cat <<'EOF'
Usage: wegame-dwproton [OPTION]

Run the official Tencent WeGame client in an isolated DWProton prefix.

Options:
  --install          Run the official installer when WeGame is not installed
  --recover-update   Apply only the confirmed update failure state
  --stop             Stop the running WeGame session (launcher and Wine processes)
  --print-prefix     Print the Wine prefix path
  --version          Print the package version
  -h, --help         Show this help

Environment overrides:
  WEGAME_DWPROTON_PROTON     Override automatic DWProton discovery
  WEGAME_DWPROTON_SHARE_DIR  Directory containing WeGameMiniLoader.exe
EOF
}

path_is_within() {
    local path root resolved_path resolved_root
    path=$1
    root=$2
    resolved_path=$(realpath -m -- "$path")
    resolved_root=$(realpath -m -- "$root")
    [[ "$resolved_path" == "$resolved_root" || "$resolved_path" == "$resolved_root/"* ]]
}

process_uses_prefix() {
    local pid=$1 environment variable value

    environment="/proc/$pid/environ"
    [[ -r "$environment" ]] || return 1

    while IFS= read -r -d '' variable; do
        case "$variable" in
            STEAM_COMPAT_DATA_PATH=*|WINEPREFIX=*) value=${variable#*=} ;;
            *) continue ;;
        esac
        value=${value%/}
        if [[ "$value" == "$compat_data" || "$value" == "$prefix" ]]; then
            return 0
        fi
    done < <(cat -- "$environment" 2>/dev/null)

    return 1
}

prefix_is_active() {
    local pid

    for pid in /proc/[0-9]*; do
        pid=${pid#/proc/}
        process_uses_prefix "$pid" && return 0
    done

    return 1
}

is_known_tgp_status() {
    local line value
    local saw_section=0 saw_perception=0 saw_guid=0
    local saw_target_version=0 saw_old_version=0 saw_check_update_type=0
    local saw_exit_op_source=0

    [[ -f "$update_status" && ! -L "$update_status" ]] || return 1

    while IFS= read -r line || [[ -n "$line" ]]; do
        line=${line%$'\r'}
        case "$line" in
            '[tgp]')
                ((saw_section == 0 && saw_perception == 0 && saw_guid == 0 &&
                  saw_target_version == 0 && saw_old_version == 0 &&
                  saw_check_update_type == 0 && saw_exit_op_source == 0)) || return 1
                saw_section=1
                ;;
            Perception=*)
                ((saw_section == 1 && saw_perception == 0)) || return 1
                [[ "$line" == 'Perception=true' || "$line" == 'Perception=false' ]] ||
                    return 1
                saw_perception=1
                ;;
            Guid=*)
                ((saw_section == 1 && saw_guid == 0)) || return 1
                value=${line#Guid=}
                [[ "$value" =~ ^[[:xdigit:]]{8}-[[:xdigit:]]{4}-[[:xdigit:]]{4}-[[:xdigit:]]{4}-[[:xdigit:]]{12}$ ]] ||
                    return 1
                saw_guid=1
                ;;
            TargetVersion=*)
                ((saw_section == 1 && saw_target_version == 0)) || return 1
                [[ "$line" == 'TargetVersion=' ]] || return 1
                saw_target_version=1
                ;;
            OldVersion=*)
                ((saw_section == 1 && saw_old_version == 0)) || return 1
                value=${line#OldVersion=}
                [[ "$value" =~ ^[0-9]+(\.[0-9]+){1,3}$ ]] || return 1
                saw_old_version=1
                ;;
            CheckUpdateType=*)
                ((saw_section == 1 && saw_check_update_type == 0)) || return 1
                [[ "$line" == 'CheckUpdateType=0' ||
                   "$line" == 'CheckUpdateType=1' ]] || return 1
                saw_check_update_type=1
                ;;
            ExitOpSource=*)
                ((saw_section == 1 && saw_exit_op_source == 0)) || return 1
                value=${line#ExitOpSource=}
                [[ "$value" =~ ^[0-9]+$ ]] || return 1
                saw_exit_op_source=1
                ;;
            *)
                return 1
                ;;
        esac
    done < "$update_status"

    ((saw_section == 1 && saw_perception == 1 && saw_guid == 1 &&
      saw_target_version == 1 && saw_old_version == 1 &&
      saw_check_update_type == 1))
}
is_confirmed_failure_status() {
    local status_path=$1 line
    local overwrite_status='' tick_move_file=''

    [[ -f "$status_path" && ! -L "$status_path" ]] || return 1
    while IFS= read -r line || [[ -n "$line" ]]; do
        line=${line%$'\r'}
        case "$line" in
            OverwriteStatus=*)
                if [[ -n "$overwrite_status" &&
                      "$overwrite_status" != "${line#OverwriteStatus=}" ]]; then
                    return 1
                fi
                overwrite_status=${line#OverwriteStatus=}
                ;;
            TickMoveFile=*)
                if [[ -n "$tick_move_file" &&
                      "$tick_move_file" != "${line#TickMoveFile=}" ]]; then
                    return 1
                fi
                tick_move_file=${line#TickMoveFile=}
                ;;
        esac
    done < "$status_path"

    [[ "$overwrite_status" == '7299004' && "$tick_move_file" == '-1' ]]
}



classify_update() {
    local -a payload_entries=()

    if [[ ! -e "$update_payload" && ! -L "$update_payload" ]]; then
        [[ ! -e "$update_status" && ! -L "$update_status" ]] && return 1
        is_known_tgp_status && return 1
        return 2
    fi

    if [[ ! -f "$update_status" || -L "$update_status" ||
          ! -d "$update_payload" || -L "$update_payload" ]]; then
        return 2
    fi

    if is_known_tgp_status; then
        [[ -r "$update_payload" && -x "$update_payload" ]] || return 2
        shopt -s nullglob dotglob
        payload_entries=("$update_payload"/*)
        shopt -u nullglob dotglob
        # An empty staging directory must not block independent component recovery.
        ((${#payload_entries[@]} == 0)) && return 1

        [[ -f "$update_payload/wegame.exe" &&
           ! -L "$update_payload/wegame.exe" ]] || return 2
        return 3
    fi

    is_confirmed_failure_status "$update_status" || return 2
    return 0
}

relative_parent() {
    local path=$1
    if [[ "$path" == */* ]]; then
        printf '%s\n' "${path%/*}"
    else
        printf '.\n'
    fi
}

rollback_update() {
    local backup_dir=$1
    shift
    local -a applied=("$@")
    local index relative destination backup temporary

    log 'Update application failed; restoring the original files.' >&2
    for ((index=${#applied[@]} - 1; index >= 0; index--)); do
        relative=${applied[index]}
        destination="$install_dir/$relative"
        backup="$backup_dir/overwritten/$relative"

        if [[ -f "$backup" ]]; then
            temporary=$(mktemp --tmpdir="${destination%/*}" '.wegame-dwproton-rollback.XXXXXXXX') || continue
            if cp --preserve=mode,timestamps -- "$backup" "$temporary"; then
                mv -f -- "$temporary" "$destination" || true
            else
                rm -f -- "$temporary"
            fi
        else
            rm -f -- "$destination"
        fi
    done
}

restore_pending_update() {
    local backup_dir=$1 payload_path=$2 status_path=$3 payload_name=$4

    if [[ -d "$backup_dir/$payload_name" && ! -e "$payload_path" ]]; then
        mv -- "$backup_dir/$payload_name" "$payload_path" || true
    fi
    if [[ -f "$backup_dir/update.tmp" && ! -e "$status_path" ]]; then
        mv -- "$backup_dir/update.tmp" "$status_path" || true
    fi
}

apply_confirmed_update() {
    local payload_path=$1 status_path=$2 label=$3 require_client=$4
    local source relative destination backup destination_parent temporary
    local backup_dir payload_name
    local -a source_files=() applied=() overwritten=() created=()

    prefix_is_active && die 'Stop WeGame before recovering its update.'
    path_is_within "$install_dir" "$prefix" ||
        die 'The WeGame directory resolves outside the package prefix.'
    path_is_within "$payload_path" "$install_dir" ||
        die 'The update payload resolves outside the WeGame directory.'
    path_is_within "$status_path" "$install_dir" ||
        die 'The update status resolves outside the WeGame directory.'
    [[ -d "$payload_path" && ! -L "$payload_path" ]] ||
        die "The confirmed update payload is not a regular directory: '$payload_path'."
    [[ -f "$status_path" && ! -L "$status_path" ]] ||
        die "The confirmed update status is not a regular file: '$status_path'."
    if ((require_client)); then
        [[ -f "$payload_path/wegame.exe" && ! -L "$payload_path/wegame.exe" ]] ||
            die 'The confirmed update payload does not contain a regular wegame.exe.'
    fi

    shopt -s nullglob dotglob globstar
    for source in "$payload_path"/**; do
        [[ "$source" == "$payload_path" ]] && continue
        [[ ! -L "$source" ]] ||
            die "The update payload contains a symbolic link: '$source'."
        [[ -d "$source" ]] && continue
        [[ -f "$source" ]] ||
            die "The update payload contains a non-regular file: '$source'."

        relative=${source#"$payload_path"/}
        [[ -n "$relative" && "$relative" != "$source" ]] ||
            die 'Could not derive a safe update path.'
        [[ "$relative" != *$'\n'* && "$relative" != *$'\r'* ]] ||
            die 'The update payload contains an unsupported filename.'
        destination="$install_dir/$relative"
        path_is_within "$destination" "$install_dir" ||
            die "The update target escapes the WeGame directory: '$relative'."

        if [[ -e "$destination" || -L "$destination" ]]; then
            [[ -f "$destination" && ! -L "$destination" ]] ||
                die "The update would replace a non-regular path: '$relative'."
            overwritten+=("$relative")
        else
            created+=("$relative")
        fi
        source_files+=("$relative")
    done
    shopt -u nullglob dotglob globstar

    ((${#source_files[@]} > 0)) || die 'The update payload is empty.'

    mkdir -p -- "$backup_root"
    backup_dir=$(mktemp -d --tmpdir="$backup_root" \
        "$(date -u +%Y%m%dT%H%M%SZ)-$$-XXXXXXXX")
    mkdir -p -- "$backup_dir/overwritten"
    payload_name=${payload_path##*/}

    for relative in "${overwritten[@]}"; do
        source="$install_dir/$relative"
        backup="$backup_dir/overwritten/$relative"
        mkdir -p -- "${backup%/*}"
        cp --preserve=mode,timestamps -- "$source" "$backup"
    done

    printf '%s\n' "${overwritten[@]}" > "$backup_dir/overwritten-files.txt"
    printf '%s\n' "${created[@]}" > "$backup_dir/created-files.txt"
    printf '%s\n' "${payload_path#"$install_dir"/}" > "$backup_dir/payload-path.txt"
    printf '%s\n' "${status_path#"$install_dir"/}" > "$backup_dir/status-path.txt"

    if ! mv -- "$payload_path" "$backup_dir/$payload_name"; then
        die "Could not move the update payload into '$backup_dir'."
    fi
    if ! mv -- "$status_path" "$backup_dir/update.tmp"; then
        mv -- "$backup_dir/$payload_name" "$payload_path" || true
        die "Could not move the update status into '$backup_dir'."
    fi

    for relative in "${source_files[@]}"; do
        source="$backup_dir/$payload_name/$relative"
        destination="$install_dir/$relative"
        destination_parent=$(relative_parent "$relative")

        if ! mkdir -p -- "$install_dir/$destination_parent"; then
            rollback_update "$backup_dir" "${applied[@]}"
            restore_pending_update \
                "$backup_dir" "$payload_path" "$status_path" "$payload_name"
            die "Could not create the update target directory for '$relative'."
        fi
        if ! temporary=$(mktemp --tmpdir="${destination%/*}" \
            '.wegame-dwproton-update.XXXXXXXX'); then
            rollback_update "$backup_dir" "${applied[@]}"
            restore_pending_update \
                "$backup_dir" "$payload_path" "$status_path" "$payload_name"
            die "Could not create a temporary update file for '$relative'."
        fi
        if ! cp --preserve=mode,timestamps -- "$source" "$temporary"; then
            rm -f -- "$temporary"
            rollback_update "$backup_dir" "${applied[@]}"
            restore_pending_update \
                "$backup_dir" "$payload_path" "$status_path" "$payload_name"
            die "Could not stage the update file '$relative'."
        fi
        if ! mv -f -- "$temporary" "$destination"; then
            rm -f -- "$temporary"
            rollback_update "$backup_dir" "${applied[@]}"
            restore_pending_update \
                "$backup_dir" "$payload_path" "$status_path" "$payload_name"
            die "Could not install the update file '$relative'."
        fi
        applied+=("$relative")
    done

    update_recovered=1
    log "Recovered the confirmed $label. Backup: $backup_dir"
}

recover_nested_updates() {
    local multi_group="$install_dir/multi_group"
    local version_path version_name slot_path slot_name
    local status_path payload_path
    local -a version_paths=() slot_paths=()

    [[ -e "$multi_group" || -L "$multi_group" ]] || return 0
    [[ -d "$multi_group" && ! -L "$multi_group" ]] ||
        die "The WeGame component update root is not a regular directory: '$multi_group'."

    shopt -s nullglob
    version_paths=("$multi_group"/*)
    shopt -u nullglob
    for version_path in "${version_paths[@]}"; do
        version_name=${version_path##*/}
        [[ "$version_name" =~ ^[0-9]+(\.[0-9]+){1,3}$ ]] || continue
        [[ -d "$version_path" && ! -L "$version_path" ]] ||
            die "The WeGame component version path is unsafe: '$version_path'."

        shopt -s nullglob
        slot_paths=("$version_path"/*)
        shopt -u nullglob
        for slot_path in "${slot_paths[@]}"; do
            slot_name=${slot_path##*/}
            [[ "$slot_name" =~ ^[0-9]+$ ]] || continue
            [[ -d "$slot_path" && ! -L "$slot_path" ]] ||
                die "The WeGame component update slot is unsafe: '$slot_path'."

            status_path="$slot_path/update.tmp"
            payload_path="$slot_path/update_files"
            [[ -e "$payload_path" || -L "$payload_path" ]] || continue
            [[ -d "$payload_path" && ! -L "$payload_path" ]] ||
                die "The WeGame component payload is unsafe: '$payload_path'."
            is_confirmed_failure_status "$status_path" ||
                die "Refusing an unknown or incomplete component update state in '$slot_path'."
            apply_confirmed_update \
                "$payload_path" "$status_path" 'WeGame component update' 0
        done
    done
}

recover_update() {
    local report=${1:-yes} state

    update_recovered=0
    update_managed_pending=0
    if classify_update; then
        state=0
    else
        state=$?
    fi

    case "$state" in
        0)
            apply_confirmed_update \
                "$update_payload" "$update_status" 'WeGame update' 1
            ;;
        1)
            ;;
        2)
            die "Refusing an unknown or incomplete update state in '$install_dir'."
            ;;
        3)
            update_managed_pending=1
            ;;
    esac

    recover_nested_updates
    [[ "$report" == 'yes' ]] || return 0
    if ((update_recovered == 0)); then
        if ((update_managed_pending)); then
            log 'A Tencent-managed WeGame update is pending; start WeGame to let it finish.'
        else
            log 'No pending WeGame update requires recovery.'
        fi
    fi
}

resolve_proton() {
    local candidate
    local -a candidates=(
        "$share_dir/dwproton/proton"
        '/usr/share/steam/compatibilitytools.d/dwproton/proton'
        '/usr/share/steam/compatibilitytools.d/dwproton-signed/proton'
    )

    if [[ -n "$proton" ]]; then
        [[ -x "$proton" ]] || die "DWProton was not found at '$proton'."
        return
    fi

    shopt -s nullglob
    candidates+=(
        /usr/share/steam/compatibilitytools.d/dwproton*/proton
        "$data_home/lutris/runners/wine"/dwproton*/proton
        "$data_home/Steam/compatibilitytools.d"/dwproton*/proton
        "$data_home/steam/compatibilitytools.d"/dwproton*/proton
        "$HOME/.steam/root/compatibilitytools.d"/dwproton*/proton
    )
    shopt -u nullglob

    for candidate in "${candidates[@]}"; do
        if [[ -x "$candidate" ]]; then
            proton=$candidate
            log "Using DWProton: $proton"
            return
        fi
    done

    die 'DWProton was not found. Reinstall wegame-dwproton or set WEGAME_DWPROTON_PROTON.'
}

run_proton_command() {
    resolve_proton

    mkdir -p -- "$compat_data" "$steam_root" "$cache_dir/dxvk"

    env \
        STEAM_COMPAT_DATA_PATH="$compat_data" \
        STEAM_COMPAT_CLIENT_INSTALL_PATH="$steam_root" \
        WINEPREFIX="$prefix" \
        DXVK_STATE_CACHE_PATH="$cache_dir/dxvk" \
        SteamAppId="$STEAM_APP_ID" \
        SteamGameId="$STEAM_APP_ID" \
        "$proton" "$@"
}

configure_prefix() {
    if [[ -e "$prefix_config_marker" || -L "$prefix_config_marker" ]]; then
        [[ -f "$prefix_config_marker" && ! -L "$prefix_config_marker" ]] ||
            die "Refusing an invalid prefix configuration marker at '$prefix_config_marker'."
        return 0
    fi

    log 'Disabling the Wine fallback system tray.'
    run_proton_command run reg.exe add \
        'HKCU\Software\Wine\Explorer' \
        /v ShowSystray /t REG_DWORD /d 0 /f
    touch -- "$prefix_config_marker"
}

choose_nested_display() {
    local number
    for number in {100..199}; do
        if [[ ! -e "/tmp/.X${number}-lock" &&
              ! -S "/tmp/.X11-unix/X${number}" ]]; then
            printf ':%s\n' "$number"
            return
        fi
    done
    die 'No free nested X11 display is available.'
}


stop_child() {
    local pid=${1:-}
    [[ -n "$pid" ]] || return 0
    kill "$pid" >/dev/null 2>&1 || true
    wait "$pid" >/dev/null 2>&1 || true
}


proton_wineserver() {
    printf '%s/files/bin/wineserver\n' "${proton%/*}"
}


stop_prefix_for_transition() {
    local wineserver
    local -a leftovers=()

    wineserver=$(proton_wineserver)
    [[ -x "$wineserver" ]] ||
        die "DWProton wineserver was not found at '$wineserver'."
    WINEPREFIX="$prefix" "$wineserver" -k >/dev/null 2>&1 || true
    WINEPREFIX="$prefix" timeout 30 "$wineserver" -w >/dev/null 2>&1 ||
        die 'The previous Wine desktop did not stop during the display transition.'

    mapfile -t leftovers < <(prefix_pids)
    ((${#leftovers[@]} == 0)) && return 0
    log 'Stopping processes left over from the previous Wine desktop.'
    signal_processes TERM "${leftovers[@]}"
    wait_for_processes 20 "${leftovers[@]}" && return 0
    signal_processes KILL "${leftovers[@]}"
    wait_for_processes 20 "${leftovers[@]}" ||
        die 'The previous Wine desktop did not stop during the display transition.'
}


run_proton_session() {
    local display_name=$1 helper_pid=$2 transition_file=$3 target=$4
    local proton_pid helper_status helper_grace_attempt
    shift 4

    niri_transition=''
    niri_exit_code=0
    env \
        DISPLAY="$display_name" \
        STEAM_COMPAT_DATA_PATH="$compat_data" \
        STEAM_COMPAT_CLIENT_INSTALL_PATH="$steam_root" \
        WINEPREFIX="$prefix" \
        DXVK_STATE_CACHE_PATH="$cache_dir/dxvk" \
        SteamAppId="$STEAM_APP_ID" \
        SteamGameId="$STEAM_APP_ID" \
        "$proton" waitforexitandrun "$target" "$@" &
    proton_pid=$!

    while kill -0 "$proton_pid" >/dev/null 2>&1; do
        if [[ -s "$transition_file" ]]; then
            break
        fi
        if ! kill -0 "$helper_pid" >/dev/null 2>&1; then
            if wait "$helper_pid"; then
                helper_status=0
            else
                helper_status=$?
            fi
            if ((helper_status != 0)); then
                niri_transition='helper-error'
            else
                for ((helper_grace_attempt=0; helper_grace_attempt < 40; helper_grace_attempt++)); do
                    kill -0 "$proton_pid" >/dev/null 2>&1 || break
                    sleep 0.05
                done
                kill -0 "$proton_pid" >/dev/null 2>&1 &&
                    niri_transition='helper-exited'
            fi
            break
        fi
        sleep 0.05
    done

    if [[ -s "$transition_file" ]]; then
        IFS= read -r niri_transition < "$transition_file" || true
    fi
    case "$niri_transition" in
        login|main|helper-error|helper-exited)
            stop_prefix_for_transition
            ;;
        '')
            ;;
        *)
            stop_prefix_for_transition
            niri_transition='invalid'
            ;;
    esac

    if wait "$proton_pid"; then
        niri_exit_code=0
    else
        niri_exit_code=$?
    fi
    if [[ -n "$niri_transition" ]]; then
        prefix_is_active &&
            die 'The Wine prefix remained active during the display transition.'
    fi
}


start_twm() {
    local display_name=$1
    DISPLAY="$display_name" twm -f "$twm_config" &
    niri_twm_pid=$!
    sleep 0.2
    if ! kill -0 "$niri_twm_pid" >/dev/null 2>&1; then
        stop_child "$niri_xserver_pid"
        niri_twm_pid=''
        niri_xserver_pid=''
        die 'TWM could not manage the nested X11 display.'
    fi
}


run_proton_in_rootful_xwayland() {
    local transition_file=$1 target=$2
    local nested_display output_name screen_width screen_height screen_size
    shift 2

    if ! read -r output_name screen_width screen_height \
        < <("$nested_x11_fix" --print-focused-output); then
        die 'Could not read the focused niri output geometry.'
    fi
    [[ -n "$output_name" && "$screen_width" =~ ^[0-9]+$ &&
       "$screen_height" =~ ^[0-9]+$ ]] ||
        die 'The focused niri output geometry is invalid.'
    screen_size="${screen_width}x${screen_height}"
    nested_display=$(choose_nested_display)

    Xwayland "$nested_display" \
        -geometry "$screen_size" -fullscreen -output "$output_name" \
        -glamor gl -noreset -nolisten tcp -br &
    niri_xserver_pid=$!
    if ! DISPLAY="$nested_display" "$nested_x11_fix" \
        --wait-only --screen-width "$screen_width" \
        --screen-height "$screen_height" --timeout 10; then
        stop_child "$niri_xserver_pid"
        niri_xserver_pid=''
        die 'The rootful Xwayland display did not become ready.'
    fi

    start_twm "$nested_display"
    DISPLAY="$nested_display" "$nested_x11_fix" \
        --app-id "steam_app_$STEAM_APP_ID" \
        --prefix "$prefix" \
        --parent-pid "$$" \
        --mode rootful \
        --transition-file "$transition_file" \
        --login-delay "$rootful_login_delay" &
    niri_fix_pid=$!

    run_proton_session \
        "$nested_display" "$niri_fix_pid" "$transition_file" "$target" "$@"
    stop_child "$niri_fix_pid"
    stop_child "$niri_twm_pid"
    stop_child "$niri_xserver_pid"
    niri_fix_pid=''
    niri_twm_pid=''
    niri_xserver_pid=''
    return "$niri_exit_code"
}


run_proton_in_xephyr() {
    local transition_file=$1 target=$2 nested_display
    shift 2

    nested_display=$(choose_nested_display)
    Xephyr "$nested_display" \
        -screen 960x540 -dpi 96 -noreset -nolisten tcp \
        -name wegame-dwproton-nested -title WeGame -br \
        -sw-cursor -no-host-grab &
    niri_xserver_pid=$!
    if ! DISPLAY="$nested_display" "$nested_x11_fix" \
        --wait-only --screen-width 960 --screen-height 540 --timeout 10; then
        stop_child "$niri_xserver_pid"
        niri_xserver_pid=''
        die 'The Xephyr login display did not become ready.'
    fi

    start_twm "$nested_display"
    DISPLAY="$nested_display" "$nested_x11_fix" \
        --app-id "steam_app_$STEAM_APP_ID" \
        --prefix "$prefix" \
        --parent-pid "$$" \
        --mode xephyr \
        --transition-file "$transition_file" &
    niri_fix_pid=$!

    run_proton_session \
        "$nested_display" "$niri_fix_pid" "$transition_file" "$target" "$@"
    stop_child "$niri_fix_pid"
    stop_child "$niri_twm_pid"
    stop_child "$niri_xserver_pid"
    niri_fix_pid=''
    niri_twm_pid=''
    niri_xserver_pid=''
    return "$niri_exit_code"
}


cleanup_niri_children() {
    stop_child "${niri_fix_pid:-}"
    stop_child "${niri_twm_pid:-}"
    stop_child "${niri_xserver_pid:-}"
}

cleanup_session_at_exit() {
    local -a targets=()

    cleanup_niri_children
    mapfile -t targets < <(session_pids)
    ((${#targets[@]} == 0)) && return 0
    signal_processes TERM "${targets[@]}"
    wait_for_processes 20 "${targets[@]}" && return 0
    signal_processes KILL "${targets[@]}"
    wait_for_processes 20 "${targets[@]}" || true
}


run_proton_in_niri() {
    local target=$1 mode='rootful' transition_file exit_code
    local rootful_login_delay='3.0'
    shift

    resolve_proton
    mkdir -p -- "$compat_data" "$steam_root" "$cache_dir/dxvk"
    command -v Xwayland >/dev/null 2>&1 ||
        die 'Xwayland is required to run WeGame under niri.'
    command -v Xephyr >/dev/null 2>&1 ||
        die 'Xephyr is required to display the WeGame login under niri.'
    command -v twm >/dev/null 2>&1 ||
        die 'TWM is required to run WeGame under niri.'
    [[ -x "$nested_x11_fix" ]] ||
        die "The nested X11 helper is missing at '$nested_x11_fix'."
    [[ -f "$twm_config" && ! -L "$twm_config" ]] ||
        die "The TWM configuration is missing at '$twm_config'."

    transition_file=$(mktemp --tmpdir="$state_dir" 'niri-transition.XXXXXXXX')
    niri_xserver_pid=''
    niri_twm_pid=''
    niri_fix_pid=''
    trap 'cleanup_niri_children; stop_prefix_for_transition; exit 143' INT TERM HUP
    trap 'cleanup_session_at_exit' EXIT

    while true; do
        : > "$transition_file"
        if [[ "$mode" == 'rootful' ]]; then
            if run_proton_in_rootful_xwayland \
                "$transition_file" "$target" "$@"; then
                exit_code=0
            else
                exit_code=$?
            fi
        else
            if run_proton_in_xephyr "$transition_file" "$target" "$@"; then
                exit_code=0
            else
                exit_code=$?
            fi
        fi

        case "$niri_transition" in
            login)
                log 'Restarting WeGame in Xephyr for reliable login input.'
                mode='xephyr'
                rootful_login_delay='3.0'
                ;;
            main)
                log 'Restarting WeGame in rootful Xwayland for game support.'
                mode='rootful'
                rootful_login_delay='30.0'
                ;;
            '')
                rm -f -- "$transition_file"
                trap - INT TERM HUP
                return "$exit_code"
                ;;
            *)
                rm -f -- "$transition_file"
                trap - INT TERM HUP
                die 'The nested X11 helper exited without a valid display transition.'
                ;;
        esac
    done
}


run_proton() {
    local target=$1
    local desktop=${XDG_CURRENT_DESKTOP:-}
    shift

    if [[ "${desktop,,}" == *niri* ]]; then
        run_proton_in_niri "$target" "$@"
    else
        run_proton_command waitforexitandrun "$target" "$@"
    fi
}

install_wegame() {
    [[ ! -f "$client" ]] || die "WeGame is already installed in '$prefix'."
    [[ -f "$installer" ]] || die "The official installer is missing at '$installer'."

    log 'Starting the official Tencent installer.'
    log "Use the default installation directory: C:\\Program Files (x86)\\WeGame"
    configure_prefix
    run_proton "$installer"

    [[ -f "$client" ]] ||
        die "The installer did not create '$client'. Custom installation directories are unsupported."

    recover_update no

    log 'Installation finished. Start WeGame again with wegame-dwproton.'
}

process_holds_launcher_lock() {
    local pid=$1 target

    # The launcher keeps the instance lock open on descriptor 9 and every
    # descendant inherits it, so this identifies the whole launcher session.
    target=$(readlink -- /proc/"$pid"/fd/9 2>/dev/null) || return 1
    [[ "$target" == "$lock_file" ]]
}

invoking_ancestors() {
    local pid=$PPID parent line hops=0

    while [[ "$pid" =~ ^[0-9]+$ ]] && ((pid > 1)) && ((hops < 64)); do
        printf '%s\n' "$pid"
        parent=''
        while IFS= read -r line; do
            [[ "$line" == 'PPid:'* ]] || continue
            parent=${line#PPid:}
            break
        done < /proc/"$pid"/status 2>/dev/null || true
        parent=${parent//[[:space:]]/}
        [[ "$parent" =~ ^[0-9]+$ ]] || break
        pid=$parent
        ((hops++)) || true
    done
}

matched_pids() {
    local predicate=$1 pid

    for pid in /proc/[0-9]*; do
        pid=${pid#/proc/}
        "$predicate" "$pid" && printf '%s\n' "$pid"
    done
}

process_is_session_member() {
    local pid=$1

    process_uses_prefix "$pid" || process_holds_launcher_lock "$pid"
}

prefix_pids() {
    matched_pids process_uses_prefix
}

session_pids() {
    local pid excluded=' '

    while IFS= read -r pid; do
        excluded+="$pid "
    done < <(invoking_ancestors)
    excluded+="$$ "

    while IFS= read -r pid; do
        [[ "$excluded" != *" $pid "* ]] || continue
        printf '%s\n' "$pid"
    done < <(matched_pids process_is_session_member)
}

process_running() {
    local pid=$1 state='' line

    while IFS= read -r line; do
        [[ "$line" == 'State:'* ]] || continue
        state=${line#State:}
        break
    done < <(cat -- /proc/"$pid"/status 2>/dev/null) || true
    state=${state//[[:space:]]/}

    [[ -n "$state" && "$state" != 'Z' ]]
}

wait_for_processes() {
    local attempt pid
    local -a pending=()
    local steps=$1
    shift

    for ((attempt = 0; attempt < steps; attempt++)); do
        pending=()
        for pid in "$@"; do
            process_running "$pid" && pending+=("$pid")
        done
        ((${#pending[@]} == 0)) && return 0
        sleep 0.1
    done

    return 1
}

signal_processes() {
    local signal=$1 pid
    shift

    for pid in "$@"; do
        kill "-$signal" -- "$pid" 2>/dev/null || true
    done
}

stop_wegame() {
    local proton_dir wineserver count pid
    local -a targets=() remaining=()
    resolve_proton
    proton_dir=${proton%/*}
    wineserver="$proton_dir/files/bin/wineserver"

    [[ -x "$wineserver" ]] || die "DWProton wineserver was not found at '$wineserver'."
    [[ -d "$prefix" ]] || {
        log "The prefix does not exist: $prefix"
        return 0
    }

    mapfile -t targets < <(session_pids)
    count=${#targets[@]}

    WINEPREFIX="$prefix" "$wineserver" -k >/dev/null 2>&1 || true

    if ((count == 0)); then
        log 'No running WeGame session was found.'
        return 0
    fi

    if wait_for_processes 50 "${targets[@]}"; then
        log "Stopped the WeGame session ($count processes)."
        return 0
    fi

    log "Stopping the WeGame session ($count processes)."
    signal_processes TERM "${targets[@]}"
    if wait_for_processes 50 "${targets[@]}"; then
        log "Stopped the WeGame session ($count processes)."
        return 0
    fi

    log "Force-stopping the WeGame session ($count processes)."
    signal_processes KILL "${targets[@]}"
    if wait_for_processes 50 "${targets[@]}"; then
        log "Force-stopped the WeGame session ($count processes)."
        return 0
    fi

    remaining=()
    for pid in "${targets[@]}"; do
        process_running "$pid" && remaining+=("$pid")
    done
    die "Could not stop the WeGame session: ${remaining[*]}"
}

launch_wegame() {
    local exit_code

    [[ -f "$client" ]] || {
        install_wegame
        return
    }

    recover_update no

    configure_prefix
    if run_proton "$client"; then
        exit_code=0
    else
        exit_code=$?
    fi

    recover_update no
    if ((update_recovered)); then
        log 'Restarting WeGame once after the recovered update.'
        run_proton "$client"
        return
    fi
    if ((update_managed_pending)); then
        log 'WeGame left a Tencent-managed update pending; start WeGame again to let it finish.'
    fi

    return "$exit_code"
}

main() {
    local command=${1:-launch}

    case "$command" in
        --help|-h)
            usage
            return
            ;;
        --version)
            printf '%s %s\n' "$APP_ID" "$PACKAGE_VERSION"
            return
            ;;
        --print-prefix)
            printf '%s\n' "$prefix"
            return
            ;;
        --stop)
            stop_wegame
            return
            ;;
        launch|--install|--recover-update)
            ;;
        *)
            usage >&2
            die "Unknown option: $command"
            ;;
    esac

    mkdir -p -- "$state_dir"
    exec 9> "$state_dir/launcher.lock"
    flock -n 9 || die 'Another WeGame launcher instance is active.'

    case "$command" in
        launch) launch_wegame ;;
        --install) install_wegame ;;
        --recover-update) recover_update ;;
    esac
}

main "$@"