#!/usr/bin/python3
## -*- coding: utf-8 -*-
#
#
# Copyright (C) 2011, Thomas Mashos, for Mythbuntu
#
#
# Mythbuntu-bare is free software; you can redistribute it and/or modify it under
# the terms of the GNU General Public License as published by the Free
# Software Foundation; either version 2 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 General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this application; if not, write to the Free Software Foundation, Inc., 51
# Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
##################################################################################

import shutil
import os
import time
import tarfile
import logging
import subprocess

logger = logging.getLogger('mythbuntu-bare')
hdlr = logging.FileHandler('/var/log/mythbuntu-bare-client.log')
formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
hdlr.setFormatter(formatter)
logger.addHandler(hdlr) 
logger.setLevel(logging.WARNING)

ACTOR="<mythbackup> "

class Restore():

    def restore_job(self, Location, RestoreDB):
        logger.info(ACTOR+'Starting restore job')
        USER=os.getenv("HOME")
        ## Set temp directory and status file
        TMPDIR="/tmp/mythbuntu-bare/"
        STATUSFILE="/tmp/mythbuntu-bare-status"
        ##Remove temp DB dir and statusfile first in case it already exists
        if os.path.exists(STATUSFILE):
            os.remove(STATUSFILE)
        if os.path.exists(TMPDIR):
            shutil.rmtree(TMPDIR)
        ## Open and Extract tarfile
        os.system("echo '30\nRestoring configuration files'>"+STATUSFILE)
        logger.info(ACTOR+'Restoring files from '+str(Location))
        TF=tarfile.open(Location,mode='r')
        TF.extractall(path="/", members=None)
        TF.close()
        ## Update mythtv db password with backed up password
        logger.info(ACTOR+'Reconfiguring mythtv-database')
        os.system("DEBIAN_FRONTEND=noninteractive dpkg-reconfigure mythtv-database")
        logger.info(ACTOR+'Detecting Master Backend')
        if os.path.isdir("/usr/share/doc/mythtv-backend-master"):
            logger.info(ACTOR+'Master Backend: True')
            if RestoreDB == True or RestoreDB == "True" or RestoreDB == 1:
                logger.info(ACTOR+'Restoring Database: True')
                os.system("echo '40\nRestoring database (this could take a few minutes)'>"+STATUSFILE)
                ##TODO
                restorescript="/usr/share/mythtv/mythconverg_restore.pl"
                pipe = subprocess.Popen([restorescript, '--drop_database', '--create_database', '--directory', TMPDIR], stdout=subprocess.PIPE).communicate()
            else:
                logger.info(ACTOR+'Restoring Database: False')
        else:
            logger.info(ACTOR+'Master Backend: False')
        ## Remove Temp directory and status file
        os.system("echo '90\nCleaning up temp files'>"+STATUSFILE)
        time.sleep(1)
        logger.info(ACTOR+'Cleaning up temp files')
        if os.path.exists(TMPDIR):
            shutil.rmtree(TMPDIR)
        if os.path.exists(STATUSFILE):
            os.remove(STATUSFILE)
        logger.info(ACTOR+'Restore job finished')
