#! /bin/bash

temp="/tmp/answer.$$"
prog="${0##*/}"
ver="0.1"
configfile="myconfig.h"
configfile_sample="myconfig-sample.h"

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 !" 0 0
      exit 1
    fi
    cp $configfile_sample $configfile
    dialog --title " Message " --msgbox "Created $configfile from $configfile_sample !" 0 0
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 !" 0 0
   exit 1
fi
dialog --checklist 'tag feature(s) to choose' 0 0 0 $menulist 2>$temp
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~
