#!/usr/bin/env python

import sys,re

from systematic.shell import Script,ScriptError
from subprocess import check_output,CalledProcessError
from seine.route import IPRoutingTable,RoutingTableError

script = Script()
script.add_argument('--mac',action='store_true',help='Just show gw mac address')
script.add_argument('addresses',nargs='*',help='Addresses to lookup')
args = script.parse_args()

iprt = IPRoutingTable()

for address in args.addresses:
    try:
        script.log.debug('Lookup %s' % address)
        route = iprt.best_route(address)

        if route is not None:
            if args.mac:
                if route.gateway_mac_address:
                    script.message(route.gateway_mac_address)
                else:
                    script.log.debug('No gateway for %s' % (address))
            else:
                script.message('%s gw mac %s' % (route,route.gateway_mac_address))
        else:
            self.log.debug('No route to %s' % address)
            script.exit(1)

    except RoutingTableError,emsg:
        script.message('Error looking up best route to %s: %s' % (address,emsg))
