#!/bin/bash
# Author: Steven Shiau <steven _at_ nchc org tw>
# License: GPL

get_block_line_in_gdm() {
     local session="$1"
     local CFG_FILE="$2"
     [ -f "$CFG_FILE" ] || exit 1
     # Turn on the Enable=true in [xdmcp]
     # Enable=true
     # By using
     # grep -n "^\[.*\]" gdm.conf |grep -A1 "\[xdmcp\]"                 
     # We can get the results like:
     # 175:[xdmcp]
     # 210:[gui]
     # so we know we can replace the one between line no. 175 and 210
     between_lines=$(grep -n "^\[.*\]" $CFG_FILE |grep -i -A1 "\[$session\]" | cut -d":" -f1)
     begin_line=$(echo $between_lines | awk -F" " '{print $1}')
     end_line=$(echo $between_lines | awk -F" " '{print $2}')
     # if end_line is nothing, it must be the last block, i.e. we can not find the next [.*]
     if [ -z "$end_line" ]; then
       end_line=$(wc -l $CFG_FILE | awk -F" " '{print $1}')
     else
       # if not nothing, backword one line
       end_line=$(($end_line - 1))
     fi
     echo "$begin_line $end_line"
}

bl=$1
#GDM_CFG=/etc/gdm/custom.conf
GDM_CFG=custom.conf
lines="$(get_block_line_in_gdm $bl $GDM_CFG)"
#lines=$(get_xdmcp_block $GDM_CFG)
begin_line=$(echo $lines | awk -F" " '{print $1}')
end_line=$(echo $lines | awk -F" " '{print $2}')
chk_cmd="if ($begin_line..$end_line) {print}"
if [ -n "$(perl -n -e "$chk_cmd" $GDM_CFG | grep -i "^AutomaticLoginEnable=")" ]; then
  #AutomaticLoginEnable=false
  #AutomaticLogin=
  sub_cmd="if ($begin_line..$end_line) {s/^AutomaticLoginEnable=.*/AutomaticLoginEnable=true/}"
  perl -pi -e "$sub_cmd" $GDM_CFG
else
  # insert 1 blank line
  sub_cmd="if ($((end_line))..$((end_line))) {s/^(.*)$/\$1\n/gi}"
  perl -pi -e "$sub_cmd" $GDM_CFG
  # replace the one we want in the added blank line
  sub_cmd="if ($((end_line+1))..$((end_line+1))) {s/^$/AutomaticLoginEnable=true/gi}"
  perl -pi -e "$sub_cmd" $GDM_CFG
fi
