#!/bin/php
<?php
$file="/etc/gdm/custom.conf";
if(isset($argv[1]) && $argv[1]=="etc-autoupdater") $file.=".etc-autoupdater";

if(!file_exists($file)){
    $dir=dirname($file);
    if(!is_dir($dir)){
        mkdir($dir,0755,true);
    }
    $fp=fopen($file,"w");
    fwrite($fp,"[daemon]\n");
    fclose($fp);
}

$settings=array();
$settings[]=array(
    "key"=>"AutomaticLoginEnable",
    "replace"=>"AutomaticLoginEnable=True"
);
$settings[]=array(
    "key"=>"AutomaticLogin",
    "replace"=>"AutomaticLogin=autologin"
);
$settings[]=array(
    "key"=>"WaylandEnable",
    "replace"=>"WaylandEnable=true"
);
$settings[]=array(
    "key"=>"DefaultSession",
    "replace"=>"DefaultSession=gnome.desktop"
);

$original=file($file);
$new="";
$in_daemon=false;
$daemon_seen=false;
$done=array();
$inserted_before_next_section=false;

foreach($original as $line){
    $trim=trim($line);
    if(strlen($trim)>1 && substr($trim,0,1)=="[" && substr($trim,-1)=="]"){
        if($in_daemon && !$inserted_before_next_section){
            foreach($settings as $rid=>$arr){
                if(!in_array($rid,$done)){
                    $new.=$arr["replace"]."\n";
                    $done[]=$rid;
                }
            }
            $inserted_before_next_section=true;
        }
        $section=strtolower(substr($trim,1,strlen($trim)-2));
        $in_daemon=($section=="daemon");
        if($in_daemon){
            $daemon_seen=true;
        }
        $new.=$trim."\n";
        continue;
    }

    $newline="";
    $match=false;
    if($in_daemon){
        foreach($settings as $rid=>$arr){
            if($match) continue;
            $key=$arr["key"];
            if(fnmatch("#".$key."=*",$trim) || fnmatch($key."=*",$trim)){
                $match=true;
                $docline=explode(" -> OLD: ",$trim);
                if(isset($docline[1])){
                    $docline[0].="...(trimmed)";
                }
                $docline=$docline[0];
                if(in_array($rid,$done)){
                    $newline="# Removed by ".__FILE__." because of duplicate match -> OLD: ".$docline;
                }
                else{
                    $newline=$arr["replace"];
                    $done[]=$rid;
                }
            }
        }
    }
    if(!$match){
        $newline=$trim;
    }
    $new.=$newline."\n";
}

if(!$daemon_seen){
    if(trim($new)!=""){
        $new.="\n";
    }
    $new.="[daemon]\n";
    $in_daemon=true;
}

if($in_daemon && !$inserted_before_next_section){
    foreach($settings as $rid=>$arr){
        if(!in_array($rid,$done)){
            $new.=$arr["replace"]."\n";
            $done[]=$rid;
        }
    }
}

$fp=fopen($file,"w");
fwrite($fp,$new);
fclose($fp);
echo "Patched config file ".$file."!\r\n";
