#!/usr/bin/env python
# -*- coding: utf-8 -*-

### Hamachi Control
###
### Copyright 2007 Janek Thomaschewski <foxx@php4you.de>
### http://janek.php4you.de/
###
### Installation:
### - Speichern des Scripts als "/etc/init.d/hamachi_control"
### - Ausführbar machen mit "sudo chmod +x /etc/init.d/hamachi_control"
### - Mit dem folgenden Befehl in die Standard-Runlevel kopieren: "sudo update-rc.d hamachi_control defaults"
###
### 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.

import sys
import subprocess
import time
import os

# CONFIGURATION START #

# Der Systembenutzer für welchen Hamachi geladen werden soll
user = 'benutzername'

# Die Befehle die für die jeweiligen Vorgänge ausgeführt werden sollen. Dies kann im Regelfall unberührt bleiben.
command_start = ['sudo /sbin/tuncfg', 'su %s -c "/usr/bin/hamachi start"' % user, 'su %s -c "/usr/bin/hamachi login"' % user]
command_stop = ['sudo killall -9 /sbin/tuncfg', 'su %s -c "/usr/bin/hamachi stop"' % user]

# CONFIGURATION END #

class actions:

    def __init__(self):

	if len(sys.argv) == 1:
	    self.help()
        elif sys.argv[1] == 'start':
            self.start()
        elif sys.argv[1] == 'stop':
            self.stop()
        elif sys.argv[1] == 'restart':
            self.restart()
        else:
            self.help()

    def start(self):
        
        for i in command_start:
            p = subprocess.Popen(i, shell=True)
	    sts = os.waitpid(p.pid, 0)        

        print 'Hamachi wurde gestartet!'

    def stop(self):

        for i in command_stop:
            p = subprocess.Popen(i, shell=True)
	    sts = os.waitpid(p.pid, 0)    
        
        print 'Hamachi wurde gestoppt!'
        
    def restart(self):
        self.stop()
        time.sleep(2)
        self.start()

    def help(self):
        print 'Bitte nutze folgende Kommandos:'
        print 'start - Starten von Hamachi'
        print 'stop - Stoppen von Hamachi'
        print 'restart - Neustarten von Hamachi'
        print 'help - Diese Kurzhilfe'

if __name__ == "__main__":    
    app = actions()
