#!/bin/bash

Info () {
title="Info"
author="Peter Starfinger"
mail="E-Mail: info@die-starfingers.de"
year="2020"
app="$(basename $0)"
msgid="The Starbuntu application
<i>\$app</i>
was written by"
info="$(gettext "$msgid" | (export PATH `envsubst --variables "$msgid"`; envsubst "$msgid"))"

yad --center --fixed --title="$title" --window-icon="info" --image="info" --borders=20 --text="$info"$'\n'$'\n'"$author"$'\n'"$mail"$'\n'$'\n'"$year"$'\n' --text-align=center --selectable-labels --button="OK" &
wunwa "$title" > /dev/null; xdotool key Home key Down
}

host="$1"
[ "$host" = "info" ] && Info && exit 0
[ -z "${host// /}" ] && host="#!"
[ "$host" = "false" ] && host=$"No autologin"

IFS=$'\n'
arr=($(ls /home))
no=$"No autologin"

arr+=($no)
ready=$"Done!"
title="Autologin:"

if [[ ! ${arr[@]} =~ "$host" ]]; then
    i=${#arr[@]}
    h=$((96+24*$i))
    cancel=$"Cancel"

    host=$(yad --center --title="$title" --height=$h --borders=30 --list --no-headers --window-icon=$HOME/.icons/autologin.png --column=Host ${arr[@]} --button="$cancel":1 --button="Info":"$0 info" --button="OK":0)

    if [ $? -gt 0 ]; then exit 252; fi
    host=${host%|*}
fi

f="/etc/sddm.conf"
[ "$host" = "$no" ] && host="nobody"
a="User=.*"
b="User=$host"
[ "$USER" != "root" ] && gsu sed -i "s/$a/$b/" $f || sed -i "s/$a/$b/" $f
err=$?
if [ $err -gt 0 ]; then exit $err; fi

yad --center --title="$title" --width=200 --window-icon=$HOME/.icons/autologin.png --borders=20 --text="<b>$ready</b>"$'\n' --text-align="center" --button="OK"

