#!/bin/sh

RAMDISK="/usr/ramdisk"
FLOWEYE="${RAMDISK}/bin/floweye"


error_exit()
{
    echo "${*}"
    exit 1
}


script_help()
{
    printf "usage:\t $0 file= stat= cover= module=\n"
    exit 1
}


do_import()
{
    local ok=0
    local err=0
    local total=`cat ${API_file} | wc -l`
    local stat_file="${API_stat}.bak"
    local stat_dir=`dirname ${API_stat}`

    local add_cmd="${1}"
    local set_cmd="${2}"

    mkdir -p ${stat_dir}
    
    cat ${API_file} | while read line
    do
        errmsg=`${FLOWEYE} ${add_cmd} ${line}`

        if [ $? -ne 0 ]; then
            if [ "${API_cover}" = "cover" ]; then
                errmsg=`${FLOWEYE} ${set_cmd} ${line}`
                if [ $? -ne 0 ]; then
                    err=$((${err}+1))
                else
                    ok=$((${ok}+1))
                fi
            else
                err=$((${err}+1))
            fi
        else
            ok=$((${ok}+1))
        fi

        printf "{" > ${stat_file}
        printf "\"ok\":${ok}" >> ${stat_file}
        printf ",\"err\":${err}" >> ${stat_file}
        printf ",\"total\":${total}" >> ${stat_file}
        printf ",\"time\":`date +%s`" >> ${stat_file}
        printf "}" >> ${stat_file}

        mv ${stat_file} ${API_stat}
    done

    rm -rf ${API_file}
}


import_route()
{
    if [ ! -f "${API_file}" ]; then
        error_exit "${API_file} not found"
    fi

    errmsg=`grep "^id=" ${API_file}`
    if [ "${errmsg}" = "" ]; then
        rm -rf "${API_file}"
        error_exit "INV_FILE"
    fi

    errmsg=`grep " action=" ${API_file}`
    if [ "${errmsg}" = "" ]; then
        rm -rf "${API_file}"
        error_exit "INV_FILE"
    fi

    do_import "route add" "route set"
}


import_portmap()
{
    if [ ! -f "${API_file}" ]; then
        error_exit "${API_file} not found"
    fi

    errmsg=`grep "id=" ${API_file}`
    if [ "${errmsg}" = "" ]; then
        rm -rf "${API_file}"
        error_exit "INV_FILE"
    fi

    errmsg=`grep " wan=" ${API_file}`
    if [ "${errmsg}" = "" ]; then
        rm -rf "$API_file}"
        error_exit "INV_FILE"
    fi

    errmsg=`grep " port=" ${API_file}`

    if [ "${errmsg}" = "" ]; then
        rm -rf "${API_file}"
        error_exit "INV_FILE"
    fi

    do_import "nat addportmap" "nat setportmap"
}


main()
{
    [ $# -lt 1 ] && script_help

    for val in $@
    do
        export "API_${val}"
    done

    case ${API_module} in
        "route")
            import_route
            ;;

        "portmap")
            import_portmap
            ;;

        *)
            echo "UNKNOW_MODULE"
            exit 1
            ;;
    esac
}


main $*
