#!/bin/bash

function set_ini() {
    # 函数使用说明：
    #   set_ini <文件> <节> <键> <值>
    #   如果节或者键不存在，则添加
    #   如果节、键存在，值不匹配，则更新
    #   如果节、键、值均存在，则不做操作

    allSections=$(awk -F '[][]' '/\[.*]/{print $2}' $1)
    iniSections=(${allSections// /})
    # 判断是否要新建item
    itemFlag="0"
    for temp in ${iniSections[@]}; do
        if [[ "${temp}" = "$2" ]]; then
            itemFlag="1"
            break
        fi
    done

    if [[ "$itemFlag" = "0" ]]; then
        echo "[$2]" >>$1
    fi

    # 加入或更新value
    awk "/\[$2\]/{a=1}a==1" $1 | sed -e '1d' -e '/^$/d' -e 's/[ \t]*$//g' -e 's/^[ \t]*//g' -e '/\[/,$d' | grep "$3.\?=" >/dev/null
    if [[ "$?" -eq 0 ]]; then
        # 更新
        # 找到指定item行号码
        itemNum=$(sed -n -e "/\[$2\]/=" $1)
        sed -i "${itemNum},/^\[.*\]/s/\($3=\).*/\1$4/g" $1 >/dev/null 2>&1
        # sed -i "${itemNum},/^\[.*\]/s/\($3.\?=\).*/\1$4/g" $1 >/dev/null 2>&1
        # 如果替换失败，可能文件中有\，更换分隔符为!
        if [[ "$?" -ne 0 ]]; then
            sed -i "${itemNum},/^\[.*\]/s!\($3=\).*!\1$4!g" $1
            # sed -i "${itemNum},/^\[.*\]/s!\($3.\?=\).*!\1$4!g" $1
        fi
    else
        # 新增
        sed -i "/^\[$2\]/a\\$3=$4" $1
    fi
    sed -i '/^#/d;/^$/d' "$1"
}

function get_ini() {
    INIFILE=$1
    SECTION=$2
    ITEM=$3
    _readIni=$(awk -F '=' '/\['${SECTION}'\]/{a=1}a==1&&$1~/'${ITEM}'/{print $2;exit}' ${INIFILE})
    echo ${_readIni}
}

function del_ini_keyV() {
    allSections=$(awk -F '[][]' '/\[.*]/{print $2}' $1)
    iniSections=(${allSections// /})
    # 判断是否要新建item
    itemFlag="0"
    for temp in ${iniSections[@]}; do
        if [[ "${temp}" = "$2" ]]; then
            itemFlag="1"
            break
        fi
    done
    if [[ "$itemFlag" = "0" ]]; then
        echo "$1 - [$2] Not Exist"
        exit 1
    fi
    # 加入或更新value
    awk "/\[$2\]/{a=1}a==1" $1 | sed -e '1d' -e '/^$/d' -e 's/[ \t]*$//g' -e 's/^[ \t]*//g' -e '/\[/,$d' | grep "$3=" >/dev/null
    if [[ "$?" -eq 0 ]]; then
        # 删除
        itemNum=$(sed -n -e "/\[$2\]/=" $1)
        sed -i "${itemNum},/^\[.*\]/s/\($3=\).*//g" $1
        sed -i '/^$/d' $1
    else
        # 没有相关项
        echo "$1 - [$2]/$3 Not Exist"
    fi
}

function get_ini_key() {
    INIFILE=$1
    SECTION=$2
    ITEM=${@:3}
    _readIni=$(awk -F '=' '/\['${SECTION}'\]/{a=1}a==1&&$2~/'"${ITEM//\//\\/}"'/{print $1;exit}' ${INIFILE})
    echo ${_readIni}
}

function main() {
    if [ "$1" == "get" ]; then
        get_ini "${@:2}"
    elif [ "$1" == "set" ]; then
        set_ini "${@:2}"
    elif [ "$1" == "del" ]; then
        del_ini_keyV "${@:2}"
    elif [ "$1" == "getkey" ]; then
        get_ini_key "${@:2}"
    else
        echo "ERROR"
    fi
}

main "$@"
