#!/usr/bin/env bash
#
# Wrapper for editing DayZ types.xml using xmlstarlet
#
#----------------------------------------------------------

# example: swap_flag M16A2 count_in_cargo 1 file
swap_flag() {
    file=$4

    if ! command -v xmlstarlet >/dev/null ; then
        >&2 echo "NOT IN \$PATH: xmlstarlet"
        exit 1
    fi

    if [ ! -f "$file" ] ; then
        >&2 echo "File: '$file' is not a file"
        exit 1
    fi

    if [ "$1" ] && [ "$2" ] && [ "$3" ] ; then
        _name=$1
        _flag=$2
        _value=$3
        xmlstarlet ed -P -L \
            -u \ "//types/type[@name=\"$_name\"]/flags[@$_flag]/@$_flag" \
            -v  \
            "$_value" \
            "$file"
    else
        >&2 echo "Bad params in swap_flag"
        exit 1
    fi
}

# example: swap_value M4A1 nominal 3 file
swap_value() {
    file=$4

    if ! command -v xmlstarlet >/dev/null ; then
        >&2 echo "NOT IN \$PATH: xmlstarlet"
        exit 1
    fi

    if [ ! -f "$file" ] ; then
        >&2 echo "File: '$file' is not a file"
        exit 1
    fi

    if [ "$1" ] && [ "$2" ] && [ "$3" ] ; then
        _name=$1
        _tag=$2
        _value=$3
        xmlstarlet ed -P -L \
            -u \ "//types/type[@name=\"$_name\"]/$_tag" \
            -v  \
            "$_value" \
            "$file"
    else
        >&2 echo "Bad params in swap_value"
        exit 1
    fi
}

usage() {
cat <<EOF
Usage: ${0##*/} [-f|-v] name tag value file

-f     swap a flag from flags
-v     swap a normal value

# --------------------------------
# Examples
# --------------------------------

# examples #1:

<type name="M16A2">
        <lifetime>28800</lifetime>
</type>

${0##*/} -v M16A2 lifetime 20000 some_file.xml

# example #2:

<type name="M16A2">
        <flags count_in_cargo="0" count_in_hoarder="0" count_in_map="1" count_in_player="0" crafted="0" deloot="0"/>
</type>

${0##*/} -f M16A2 count_in_player 1 some_file.xml

EOF
exit 1
}

if [ "$DEBUG" ] ; then
    echo "ADJUSTING TYPE: $2 $3"
fi

case $1 in
    -h|--help)
        usage
        ;;
    -f)
        shift
        swap_flag "$1" "$2" "$3" "$4" || exit 1
        ;;
    -v)
        shift
        swap_value "$1" "$2" "$3" "$4" || exit 1
        ;;
esac
