# usage: awk -f modifyini.awk S1=SECTION1 K1=KEY1 V1=XXX config.ini

BEGIN{blnFS=0;OUTF=""}

{
#do sharp
LSHARP1=""
LSHARP2=""
LSHARPP=index($0,"#")-1

if(LSHARPP>=0)
{
LSHARP1=substr($0,1,LSHARPP)
LSHARP2=substr($0,LSHARPP+1)
}
else
{
LSHARP1=$0
LSHARP2=""
}
gsub(/ *$/,"",LSHARP1)
gsub(/^ */,"",LSHARP1)
#LSHARP1=toupper(LSHARP1)
##print "LSHARP1:"LSHARP1


#S1=toupper(S1)
#K1=toupper(K1)

if(blnFS==0)
{
#get section
LSECTIONP=index(LSHARP1,"[")
RSECTIONP=index(LSHARP1,"]")
SECTION1=substr(LSHARP1,LSECTIONP+1,RSECTIONP-LSECTIONP-1)
gsub(/ *$/,"",SECTION1)
gsub(/^ */,"",SECTION1)

if(SECTION1==S1)
{
blnFS=1
##print "SECTION FOUND!!!"
}

OUTF=OUTF$0"\n"

}
else
{
#if another section
if (index($0,"[")>0)
{
blnFS=0

#add
#get section
LSECTIONP=index(LSHARP1,"[")
RSECTIONP=index(LSHARP1,"]")
SECTION1=substr(LSHARP1,LSECTIONP+1,RSECTIONP-LSECTIONP-1)

if(SECTION1==S1)
{
blnFS=1
}
#add
}

KEYP=index(LSHARP1,"=")
KEY1=substr(LSHARP1,1,KEYP-1)
gsub(/ *$/,"",KEY1)
gsub(/^ */,"",KEY1)
##print "LSHARP1:"LSHARP1"KEY1:"KEY1

if(KEY1==K1)
{
##print "KEY FOUND!!!"
##print KEY1"="V1" "LSHARP2
OUTF=OUTF""KEY1"="V1" "LSHARP2"\n"}
else
{OUTF=OUTF$0"\n"}
}

}

END{print OUTF}

