#! /usr/bin/env python
#encoding=utf-8

# wakehost.py
# Simple wakeonlan wrapper in order to wake named hosts
#
# Copyright 2010 Dennis Schulmeister <dennis@developer-showcase.de>
#
# This program 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 2 of the License, or
# (at your option) any later version.
#
# This program 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, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
# MA 02110-1301, USA.

# Configuration values
HOST_FILE_URL = "http://hermes/hosts.txt"
TIMEOUT = 10

# Imported modules
import subprocess, sys, urllib2

# Function definitions
def main():
    '''
    Main routine of this script. Returns system return code.
    '''
    try:
        host_file = urllib2.urlopen(HOST_FILE_URL, None, TIMEOUT)
    except urllib2.URLError as ex:
        print str(ex)
        return 1

    try:
        hostname = sys.argv[1]
    except IndexError:
        hostname = ""

    error = False

    if hostname:
        mac = ""

        for line in host_file:
            line = line.lstrip().rstrip()
            host = line.split(" ")

            if host[3] == hostname:
                mac = host[1]
                break

        if mac:
            try:
                subprocess.call(["wakeonlan", mac])
            except OSError:
                print "OS Error: Unable to run wakeonlan"
                error = True
        else:
            print "Unknown host: %s" % hostname
            error = True
    else:
        for line in host_file:
            line = line.lstrip().rstrip()
            host = line.split(" ")
            print "%s: %s" % (host[1], host[3])

    host_file.close()

    if error:
        return 1
    else:
        return 0

# Program start
if __name__ == "__main__":
    sys.exit(main())
