#!/bin/sh

help() {
    cat<<EOF

Enable/Disable system wide proxy arp.

The change is not permanent (runtime only).

OPTIONS:
  
--on, --enable
    enable system wide proxy arp

--off, --disable
    disable system wide proxy arp

  --status  returns 'enabled' or 'disabled'

--ifaces, -i
    apply on|off or query status to/from these interfaces instead of system wide

EOF
}


on(){
    if [ -z "${1}" ]; then
        iface='all'
    else
        iface="${1}"
    fi
    echo 1 > /proc/sys/net/ipv4/conf/${iface}/proxy_arp || return 1
    return 0
}

off(){
    if [ -z "${1}" ]; then
        iface='all'
    else
        iface="${1}"
    fi
    echo 0 > /proc/sys/net/ipv4/conf/${iface}/proxy_arp || return 1
    return 0
}

status(){
    if [ -z "${1}" ]; then
        iface='all'
    else
        iface="${1}"
    fi
    s="$(cat /proc/sys/net/ipv4/conf/${iface}/proxy_arp 2>/dev/null)"
    if [ "${s}" = "1" ]; then
        echo 'enabled'
    else
        echo 'disabled'
    fi
    return 0
}

for_each_interface() {
    predicate="${1}"
    ifs="$(echo ${2} | tr ",;" " ")"
    [ -z "${2}" ] && {
        ${predicate} || return 1
        return 0
    }

    for ifname in ${ifs}; do
        eval "${predicate} ${ifname}" || return 1
    done
    return 0
}


##
#  MAIN
##

command=''
interfaces=''

SHORTOPTS='hi:'
LONGOPTS="help,on,off,status,enable,disable,iface:"
ARGS=$(getopt -s bash --options ${SHORTOPTS} --longoptions ${LONGOPTS} -- "$@" )
eval set -- "$ARGS"
while true; do
    case $1 in
        -h|--help) help; exit 0 ;;
        --on|--enable) command="on" ;;
        --off|--disable) command="off" ;;
        --status) command="status" ;;
        -i|--iface) shift; interfaces="${1}" ;;
        --)        shift; break ;;
        *)         break ;;
    esac
    shift
done

case ${command} in
    "on")
        for_each_interface on "${interfaces}" || exit 1 ;;
    "off")
        for_each_interface off "${interfaces}" || exit 1 ;;
    "status")
        for_each_interface status "${interfaces}" || exit 1 ;;
    *)
        echo 'please provide a supported command'
        exit 1 ;;
esac

exit 0
