#!/usr/bin/perl -w
#
# update_wdm_wmlist,
#
# This script will read the list of installed window managers from
# the update-alternatives output for the x-window-manager alternative
# and update the DisplayManager*wdmWm resource in $wdm_list_file (see below).
# BEWARE: It doesn't ask any questions about this. It just does it. It
# takes an optional list of window managers.
#
# Original program:
#    Copyright (C) 1998 Marcelo Magallón <mmagallo@debian.org>
# Rewriten to use the x-window-manager alternative.
#    Copyright (C) 2000 Wichert Akkerman <wakkerma@debian.org>
# Modified to also use x-session-manager alternative.
#    Copyright (C) 2001 Arthur Korn.
# Modified to write output to a separate file.
#    Copyright (C) 2010 Agustin Martin Domingo <agmartin@debian.org>
# Refactored for modern Perl code
#    Copyright (C) 2017 Axel Beckert <abe@debian.org>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.

use strict;
use warnings;
use 5.010;

my %wm_list         = ();
my $wdm_list_string = '';
my $wdm_list_file   = '/etc/X11/wdm/wdm.wmlist';

if (@ARGV) {
    # Use provided list of window managers as is, with no extra sorting
    $wdm_list_string = join(':', @ARGV);
} else {
    foreach my $alternative ( qw(x-window-manager x-session-manager) ) {
        next unless -e "/etc/alternatives/$alternative";
        open(my $WINDOW_MANAGERS, '-|', "update-alternatives --display $alternative")
            or die "Can't run update-alternatives: $!";

        while (<$WINDOW_MANAGERS>) {
            $wm_list{$1}++ if ( m{^/.*/([^/]+) - });
        }
        close($WINDOW_MANAGERS);
    }
    # "default" should go first
    $wdm_list_string = join(':', 'default', sort keys %wm_list);
}

open(my $WDM_WMLIST_FILE, '>', $wdm_list_file)
    or die "Can't open $wdm_list_file for writing: $!";

print $WDM_WMLIST_FILE <<EOT;
! This file has been automatically generated by $0 script.
!
! Manual changes below will be overwritten on every wdm start/stop.
!     See wdm-config file to override automatic values.
!
DisplayManager*wdmWm:  $wdm_list_string
EOT

close($WDM_WMLIST_FILE);

exit 0;
