########################################################################
#
#  Copyright (C) 2009, CZ.NIC, z.s.p.o.
# 
#  This file is part of dnstester.
#
#  dnstester is free software: you can redistribute it and/or modify
#  it under the terms of the GNU General Public License as published by
#  the Free Software Foundation, either version 3 of the License, or
#  (at your option) any later version.
#
#  dnstester is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#
#  You should have received a copy of the GNU General Public License
#  along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
########################################################################

from subprocess import Popen, PIPE
import sys, time, string, traceback
import misc
from misc import readall

def detect_gateway():
    
    try:
        route = Popen(args=['/sbin/route', '-n'], stdout=PIPE, stderr=PIPE)
        retcode = route.wait()
        ferr = route.stderr
        log = readall(ferr)
    except Exception, e:
        retcode = -1
        log = traceback.format_exc()

    if retcode == 0:

        fout=route.stdout
        line = fout.readline()
        while line != "":
            columns = line.split()
            if len(columns) >= 2:
                if columns[0] == '0.0.0.0':
                    gateway = string.strip(columns[1])
                    break
            line = fout.readline()

        return gateway, log
    else:
        return None, log

def get_arp(ip):

    executable = misc.which('arp', ('/sbin', '/usr/sbin'))
    if not executable:
        return None, 'arp binary not found.'
    
    try:
        route = Popen(args=[executable, '-n'], stdout=PIPE, stderr=PIPE)
        retcode = route.wait()
        ferr=route.stderr
        log = readall(ferr)
    except:
        retcode = -1
        log = traceback.format_exc()

    if retcode == 0:

        mac = '00:00:00:00:00:00'

        fout=route.stdout
        line = fout.readline()
        while line != "":
            columns = string.split(line)
            if columns[0] == ip:
                mac = string.strip(columns[2])
                break
            line = fout.readline()

        return mac, log
    else:
        return None, log

def get_gateway_ipmac():

    gateway, route_log = detect_gateway()
    log = "Route log:\n" + route_log

    if not gateway:
        return (None, None), log

    mac, arp_log = get_arp(gateway)
    log += "ARP log:\n" + arp_log

    return (gateway, mac), log

