#!/usr/bin/python

import sys
import shutil
from subprocess import call

bootstraps = []


def delete_instance(name):
    print("Removing instance {}".format(name))
    if not call(["nova", "--insecure", "delete", name]) == 0:
        print("Failed :(")


def delete_bootstrap(*infos):
    id, date, controller1, controller2, subnet = infos
    delete_instance(controller1)
    delete_instance(controller2)
    # Remove log files
    try:
        shutil.rmtree(id)
    except OSError:
        pass
    # Remove deleted bootstrap from file
    with open('bootstraped', 'r+') as h:
        content = "\n".join(filter(lambda l: " ".join(infos) not in l, h))
        h.seek(0)
        h.truncate()
        h.write(content)


if __name__ == "__main__":

    with open('bootstraped') as h:
        bootstraps = h.readlines()
    bootstraps = [b.strip().split() for b in bootstraps]

    if not bootstraps:
        print("Nothing to unstack")
        sys.exit()

    for idx, b in enumerate(bootstraps):
        print ("{0:d} - Created {2} ({3} and {4}, {5})".format(idx, *b))

    choice = input("Your choice : ")
    try:
        infos = bootstraps[int(choice)]
    except (IndexError, ValueError):
        print("You failed.")
    else:
        delete_bootstrap(*infos)
