#!/usr/local/bin/python

"""
magic is a script to easily manage and run the updates for the 
applications your build from source.
"""

import os
from configobj import ConfigObj
import sys

CONFIG = ConfigObj(os.path.join(os.environ.get("HOME"), ".magicrc"))

try:
    SEQUENCES = CONFIG['sequences']
except KeyError:
    CONFIG['sequences'] = {}
    SEQUENCES = CONFIG['sequences']
    
CWD = os.getcwd()

def new_sequence():
    """
    new_sequence() defines a new sequence to update the application with, 
    the sequence should be something like `./configure && make && sudo make install`. Is also called when magic is passed the "-c" argument.
    """
    update_sequence = raw_input("Sequence to update the application (not \
including git pull, eg: ./configure && make && sudo make install): ")
    CONFIG['sequences'][CWD] = update_sequence
    CONFIG.write()
    is_sequence_defined()
    return None

def is_sequence_defined():
    """
    is_sequence_defined() checks if sequence is defined, if yes runs the sequence,
    if no then it calls new_sequence().
    """
    if CWD in SEQUENCES:
        os.system("cd %s && %s" % (CWD, SEQUENCES[CWD]))
    else:
        new_sequence()
    return None

if __name__ == '__main__':
    if "-c" in sys.argv:
        new_sequence()
    else:
        is_sequence_defined()
