'''
windows service for shutdown oracle server
in order to perform snapshots of VM
'''

import time
import random
from pathlib import Path
import math
import datetime as dtm
import win32serviceutil
from oraScheduleWrapper import ora_py_schedule_wrapper

ORA_SERVICE = "OracleServiceORCL"
ORA_WRITER = "OracleVssWriterORCL"


class ora_py_schedule(ora_py_schedule_wrapper):
    _svc_name_ = 'ora_py_schedule'
    _svc_display_name_ = 'Ora_Py_Schedule'
    _svc_description_ = 'Scheduled shudown/startup'

    def start(self):
        try:
            self.isrunning = True
        except Exception as e:
            raise Exception(e)

    def stop(self):
        try:
            self.isrunning = False
        except Exception as e:
            raise Exception(e)

    def main(self):
        try:
            ora_stopped = False
            while self.isrunning:
                tm = time.time()
                # tm = math.floor(tm)
                # random.seed()
                # x = random.randint(tm - 63072000, tm)
                x = math.floor(tm)
                dt = dtm.datetime.utcfromtimestamp(x)
                w = self.first_week_ofmonth(dt)
                if w:
                    if not ora_stopped:
                        win32serviceutil.StopService(ORA_SERVICE)
                        win32serviceutil.StopService(ORA_WRITER)
                        ora_stopped = True
                else:
                    ora_stopped = False
                # Path('c:\\app\\{0}-{1}-{2}_{3}_{4}.txt'.format(dt.year,
                #                                                dt.month,
                #                                                dt.day,
                #                                                w,
                #                                                dt.weekday())).touch()
                time.sleep(20)
        except Exception as e:
            raise Exception(e)

    def first_week_ofmonth(self, t=None):
        '''
        determines if actual day is satuday and
        if so, is it
        the first of actual month?
        '''
        try:
            if t is None:
                dt = dtm.datetime.utcfromtimestamp(time.time())
            else:
                dt = dtm.datetime(t.year, t.month, t.day)

            # reference date
            ref_dt = dtm.datetime(dt.year, dt.month, dt.day)
            # UTC time format is
            # 0 for monday ... 6 for sunday
            # we need saturday here
            saturday = 5

            if dt.weekday() != saturday:
                # we don't need to shutdown
                # ora database if today is not saturday
                return False
            else:
                # we assume here that actual saturday
                # is the first of actual month
                isfirst_we = True
                while isfirst_we:
                    # seek earlier saturday of month
                    if ref_dt.day > 1:
                        # don't underrun the fist of month :p
                        ref_dt = dtm.datetime(ref_dt.year,
                                              ref_dt.month,
                                              ref_dt.day - 1)
                    else:
                        # no earlier week end found on this point
                        return isfirst_we

                    if ref_dt.weekday() == saturday:
                        # earlier week end of month found,
                        # this stops while loop
                        isfirst_we = False
                    else:
                        # no earlier week end found, decrement possible
                        isfirst_we = True
                # while ends here
                return isfirst_we
        except Exception as e:
            raise e


if __name__ == '__main__':
    ora_py_schedule.parse_command_line()

'''
windows service for shutdown oracle server
in order to perform snapshots of VM
'''

import time
import random
from pathlib import Path
import math
import datetime as dtm
import win32serviceutil
from oraScheduleWrapper import ora_py_schedule_wrapper

ORA_SERVICE = "OracleServiceORCL"
ORA_WRITER = "OracleVssWriterORCL"


class ora_py_schedule(ora_py_schedule_wrapper):
    _svc_name_ = 'ora_py_schedule'
    _svc_display_name_ = 'Ora_Py_Schedule'
    _svc_description_ = 'Scheduled shudown/startup'

    def start(self):
        try:
            self.isrunning = True
        except Exception as e:
            raise Exception(e)

    def stop(self):
        try:
            self.isrunning = False
        except Exception as e:
            raise Exception(e)

    def main(self):
        try:
            ora_stopped = False
            while self.isrunning:
                tm = time.time()
                # tm = math.floor(tm)
                # random.seed()
                # x = random.randint(tm - 63072000, tm)
                x = math.floor(tm)
                dt = dtm.datetime.utcfromtimestamp(x)
                w = self.first_week_ofmonth(dt)
                if w:
                    if not ora_stopped:
                        win32serviceutil.StopService(ORA_SERVICE)
                        win32serviceutil.StopService(ORA_WRITER)
                        ora_stopped = True
                else:
                    ora_stopped = False
                # Path('c:\\app\\{0}-{1}-{2}_{3}_{4}.txt'.format(dt.year,
                #                                                dt.month,
                #                                                dt.day,
                #                                                w,
                #                                                dt.weekday())).touch()
                time.sleep(20)
        except Exception as e:
            raise Exception(e)

    def first_week_ofmonth(self, t=None):
        '''
        determines if actual day is satuday and
        if so, is it
        the first of actual month?
        '''
        try:
            if t is None:
                dt = dtm.datetime.utcfromtimestamp(time.time())
            else:
                dt = dtm.datetime(t.year, t.month, t.day)

            # reference date
            ref_dt = dtm.datetime(dt.year, dt.month, dt.day)
            # UTC time format is
            # 0 for monday ... 6 for sunday
            # we need saturday here
            saturday = 5

            if dt.weekday() != saturday:
                # we don't need to shutdown
                # ora database if today is not saturday
                return False
            else:
                # we assume here that actual saturday
                # is the first of actual month
                isfirst_we = True
                while isfirst_we:
                    # seek earlier saturday of month
                    if ref_dt.day > 1:
                        # don't underrun the fist of month :p
                        ref_dt = dtm.datetime(ref_dt.year,
                                              ref_dt.month,
                                              ref_dt.day - 1)
                    else:
                        # no earlier week end found on this point
                        return isfirst_we

                    if ref_dt.weekday() == saturday:
                        # earlier week end of month found,
                        # this stops while loop
                        isfirst_we = False
                    else:
                        # no earlier week end found, decrement possible
                        isfirst_we = True
                # while ends here
                return isfirst_we
        except Exception as e:
            raise e


if __name__ == '__main__':
    ora_py_schedule.parse_command_line()

windows service for shutdown oracle server in order to perform snapshots of VM # tm = math.floor(tm) # random.seed() # x = random.randint(tm - 63072000, tm) # Path('c:\\app\\{0}-{1}-{2}_{3}_{4}.txt'.format(dt.year, #                                                dt.month, #                                                dt.day, #                                                w, #                                                dt.weekday())).touch() determines if actual day is satuday and         if so, is it         the first of actual month? # reference date # UTC time format is # 0 for monday ... 6 for sunday # we need saturday here # we don't need to shutdown # ora database if today is not saturday # we assume here that actual saturday # is the first of actual month # seek earlier saturday of month # don't underrun the fist of month :p # no earlier week end found on this point # earlier week end of month found, # this stops while loop # no earlier week end found, decrement possible # while ends here