#!/usr/bin/env python
import sys
import time

from igs.config_manage.policy import *


def startup():
    executeTemplate('/opt/hadoop/conf/core-site.xml.tmpl')
    executeTemplate('/opt/hadoop/conf/hdfs-site.xml.tmpl')
    executeTemplate('/opt/hadoop/conf/mapred-site.xml.tmpl')
    
    #
    # Reset dfs on reboot, this should probably be fixed in future
    run('rm -rf /tmp/hadoop-root /mnt/hadoop', ignoreError=True)
    dirExists('/mnt/hadoop')
    run('hadoop namenode -format', ignoreError=True)
    dirPermissions('/mnt/hadoop', '777', ignoreError=True)

    run('/opt/hadoop/bin/hadoop-daemon.sh start namenode')
    run('/opt/hadoop/bin/hadoop-daemon.sh start datanode')
    run('/opt/hadoop/bin/hadoop-daemon.sh start jobtracker')
    run('/opt/hadoop/bin/hadoop-daemon.sh start tasktracker')
    

def shutdown():
    run('kill `cat /tmp/hadoop*tasktracker.pid`', ignoreError=True)
    run('kill `cat /tmp/hadoop*jobtracker.pid`', ignoreError=True)
    run('kill `cat /tmp/hadoop*datanode.pid`', ignoreError=True)
    run('kill `cat /tmp/hadoop*namenode.pid`', ignoreError=True)
    
if len(sys.argv) < 2:
    raise Exception('Must provide start|stop|restart')

if sys.argv[1] == 'start':
    startup()
elif sys.argv[1] == 'stop':
    shutdown()
elif sys.argv[1] == 'restart':
    shutdown()
    time.sleep(1)
    startup()
else:
    raise Exception('Unknown argument: ' + sys.argv[1])
