#!/usr/bin/python3
#
# Copyright (C) 2013-2015   Ian Firns   <firnsy@kororaproject.org>
#                           Chris Smart <csmart@kororaproject.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#

import dnf
import logging
import os
import signal
import sys
import time

logger = logging.getLogger('canvas')

# TODO: REMOVE
sys.path.append('./lib')

import canvas.config
from canvas.service import Service, ServiceException
from canvas.template import Machine, Template

CANVAS_HOST = 'https://canvas.kororaproject.org'
CANVAS_USER = os.environ.get('SUDO_USER', os.getlogin())


class Daemon():
    def __init__(self):
        self.config = canvas.config.Config()

        # create our canvas service object
        self.cs = Service(
            host=self.config.get('core', 'host', CANVAS_HOST),
            username=self.config.get('core', 'user', CANVAS_USER)
        )

        self.uuid = self.config.get('machine', 'uuid')
        self.key = self.config.get('machine', 'key')

        self.machine = None
        self.template_uuid = True
        self.template = None

    def loop(self):
        while True:
            print('Syncing ... {0}'.format(time.ctime()))

            try:
                res = self.cs.machine_sync(self.uuid, self.key, template=self.template_uuid)

            except ServiceException as e:
                print(e)
                return 1

            print(res)

            self.machine = Machine(res['machine'])

            self.template_uuid = self.machine.template

            if res['template'] is not None:
                self.template = Template(res['template'])

            print('info: machine synced.')
            print(self.machine, self.template)

            time.sleep(10)


def signal_handler(signal, frame):
    print()
    sys.exit(1)

if __name__ == '__main__':
    # trap ctrl+c, it's polish
    signal.signal(signal.SIGINT, signal_handler)

    d = Daemon()

    d.loop()
