#! /bin/bash
#
# Copyright (C) 2012,2013 The ESPResSo project
# Copyright (C) 2009,2010 Christoph Junghans
#
# This file is part of ESPResSo.
#
# ESPResSo 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 3 of the License, or
# (at your option) any later version.
#
# ESPResSo 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.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#

temp="/tmp/answer.$$"
prog="${0##*/}"
ver="0.1"
configfile="myconfig.h"
configfile_sample="myconfig-sample.h"
dialog="kdialog"
[ -z "${dialog//*kdialog*}" ] && size="0 0"

if [ -z "type -p $dialog" ]; then
   echo "dialog is missing !"
   exit 1
fi

cd ..
if [ ! -e "$configfile" ]; then
   if [ ! -e "$configfile_sample" ]; then
      $dialog --title " Error " --msgbox "No $configfile and $configfile_sample found !" $size
      exit 1
    fi
    cp $configfile_sample $configfile
    $dialog --title " Message " --msgbox "Created $configfile from $configfile_sample !" $size
fi

i=0
menulist=""
oldifs=$IFS
IFS="
"
while read line; do
    if [ -z "$line" ] || [ -n "${line/*#define*}" ]; then
       continue
    fi
    helper=${line##*#define}
    feature[$i]=${helper//[^0-9_A-Z]}
    helper=${line%%#define*}
    if [  -z "${helper//[:space:]]}" ]; then
       oldstatus[$i]="on"
    else
       oldstatus[$i]="off"
    fi
    newstatus[$i]="off"
    menulist="$menulist $i ${feature[$i]} ${oldstatus[$i]}"
    ((i++))
done <$configfile
IFS=$oldifs

if [ -z "$menulist" ]; then
   $dialog --title " Error " --msgbox "No feature(s) found !" $size
   exit 1
fi
if [ -z "${dialog//*kdialog*}" ]; then 
  $dialog --checklist 'tag feature(s) to choose' $menulist >$temp
else
  $dialog --checklist 'tag feature(s) to choose' 0 0 0 $menulist 2>$temp
fi
if [ $? != 0 ]; then
   rm $temp
   exit 1
fi

for i in $(<$temp); do
    newstatus[${i//[^0-9]}]="on"
done

mv $configfile ${configfile}~
i=0
IFS="
"
while read line; do
    if [ -z "$line" ] || [ -n "${line/*#define*}" ]; then
       echo "$line" >> $configfile
       continue
    fi
    if [ "${oldstatus[$i]}" != "${newstatus[$i]}" ]; then
       if [ "${newstatus[$i]}" = "on" ]; then
          echo "#define ${feature[$i]}" >> $configfile
       else
          echo "/* #define ${feature[$i]} */" >> $configfile
       fi
    else
       echo "$line" >> $configfile
    fi
    ((i++))
done <$configfile~
