#!/usr/bin/env python
import logging

import click
from lockfile import LockFile, LockTimeout
# Ignore error, logging set up in logging utils
from spoppy import logging_utils
from spoppy.navigation import Leifur
from spoppy.config import get_config, set_config, get_config_from_user

logger = logging.getLogger('spoppy.main')


@click.command()
@click.argument('username', required=False)
@click.argument('password', required=False)
def main(username, password):
    if username and password:
        set_config(username, password)
    else:
        username, password = get_config()
    if not (username and password):
        username, password = get_config_from_user()
    try:
        navigator = Leifur(username, password)
        navigator.start()
    finally:
        navigator.shutdown()
        logger.debug('Finally, bye!')


if __name__ == '__main__':
    lock = LockFile('/tmp/spoppy.lock')
    try:
        # Try for 5s to acquire the lock
        lock.acquire(5)
    except LockTimeout:
        click.echo('Could not acquire lock, is spoppy running?')
    else:
        main()
    finally:
        if lock.i_am_locking():
            lock.release()
