import os
import sys
import time
import traceback
import subprocess

from path import path

from mbhlib.daemonize import daemonize


__all__ = [
    'main',
]
DEFAULT_SLEEP = 1 * 60
SUP = 'git svn fetch --all'


def main(sysargs=sys.argv[:]):
    sleep_interval = DEFAULT_SLEEP
    if sys.argv[1:]:
        sleep_interval = int(sys.argv[1])
    print('running with sleep interval of %s' % sleep_interval)
    foreground = '--foreground' in sysargs[1:]
    daemon = GitSupDaemon(sleep_interval=sleep_interval, foreground=foreground)
    daemon.run()
    return 0


class GitSupDaemon(object):

    def __init__(self, basedir=path.getcwd(),
                 sleep_interval=DEFAULT_SLEEP,
                 foreground=False):
        self.updates_list = []
        self.basedir = basedir
        self.foreground = foreground
        self.sleep_interval = sleep_interval
        self.listfile = self.basedir/'.git-updates'
        self.pidfile = self.basedir/'.git-updates.pid'
        if not self.foreground:
            self.stdout = \
                (self.basedir/'.git'/'logs'/'updates.log').open('a+')
            self.stderr = \
                (self.basedir/'.git'/'logs'/'updates-errors.log').open('a+')
        else:
            self.stdout = sys.stdout
            self.stderr = sys.stderr

    def run(self):
        if not self.updates_list:
            self._get_updates_list()
        if not self.foreground:
            self._daemonize()
        while True:
            self._run_updates()
            self._sleep()

    def _get_updates_list(self):
        if not self.listfile.exists():
            self.updates_list.append(self.basedir/'.')
            return

        for line in self.listfile.lines():
            line = line.strip()
            if line and not line.startswith('#'):
                self.updates_list.append(self.basedir/line.lstrip('/'))

        self.updates_list = list(set(self.updates_list))

    def _daemonize(self):
        daemonize(stdout=self.stdout, stderr=self.stderr,
                  pidfile=self.pidfile)

    def _run_updates(self):
        for update_path in self.updates_list:
            self._run_one_update(update_path)

    def _run_one_update(self, update_path):
        try:
            os.chdir(update_path)
            subprocess.call([SUP], shell=True)
            os.chdir(self.basedir)
        except (OSError, IOError):
            traceback.print_exc()

    def _sleep(self):
        self.stdout.write('# ****  sleeping for %.2f '
                          'seconds ****\n' % self.sleep_interval)

        time.sleep(self.sleep_interval)


if __name__ == '__main__':
    sys.exit(main())

# vim:filetype=python
