from fabric.api import run,env
from fabric.operations import get,put
import os
import yaml
import re
import sys
from fabfile.db import cosmos_db
from fabric.api import task

env.user = 'root'
env.timeout = 30
env.connection_attempts = 3
env.warn_only = True
env.skip_bad_hosts = True
env.roledefs = cosmos_db()['members']
env.use_ssh_config = True

def _lookup(node_name):
    if os.path.exists(os.path.join(node_name,".hostname")):
        with open(os.path.join(node_name,".hostname"),"r") as fd:
            return fd.readline().strip()
    return node_name


@task
def all():
    env.hosts = cosmos_db()['members']['all']

@task
def h(key=None):
    db = cosmos_db()
    env.roledefs = db['members']
    if key is None:
        key = 'all'

    _hosts = [key]
    if key in env.roledefs:
        _hosts = env.roledefs[key]

    env.hosts = [ _lookup(h) for h in _hosts ]

@task
def cosmos():
    run("/usr/local/bin/run-cosmos");

@task
def set_no_automatic_cosmos():
    run("touch /etc/no-automatic-cosmos")

@task
def remove_no_automatic_cosmos():
    run("rm /etc/no-automatic-cosmos")

@task
def upgrade():
    run("apt-get -qq update && apt-get -y -q upgrade");

@task
def distupgrade():
    run("apt-get -qq update && apt-get -y -q dist-upgrade");

@task
def facts():
    get("/var/run/facts.yaml",local_path="facts/%(host)s.yaml")

@task
def chassis():
    run("ipmi-chassis --get-chassis-status")

def newvm(fqdn,ip,domain):
    run("vmbuilder kvm ubuntu --domain %s --dest /var/lib/libvirt/images/%s.img --arch x86_64 --hostname %s --mem 512 --ip %s --addpkg openssh-server" % (domain,fqdn,fqdn,ip))

@task
def cp(local,remote):
    put(local,remote)

@task
def synci():
    get("/etc/network/interfaces",local_path="%(host)s/global/overlay/etc/interfaces")