#!/usr/bin/env python
# -*- Mode: Python; indent-tabs-mode: nil; tab-width: 2; coding: utf-8 -*-
#
# This file is part of Déjà Dup.
# For copyright information, see AUTHORS.
#
# Déjà Dup 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 3 of the License, or
# (at your option) any later version.
#
# Déjà Dup 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 Déjà Dup.  If not, see <http://www.gnu.org/licenses/>.

import sys
import os
import subprocess
import stat
sys.path.insert(0, sys.path[0]+'/..')
import base
import ldtp

BASEPATH = '/tmp/deja-dup-test/'

def check_dir(path, oneval):
  root = path+BASEPATH
  assert base.file_equals(root+'one', oneval)
  assert base.file_equals(root+'two', 'two\n')
  assert base.file_equals(root+'three', 'three\n')
  assert base.file_equals(root+'top/one', 'one\n')
  assert os.path.isdir(root+'top/next')

def test():
  restoredir = base.get_temp_name('restore', make=True)
  os.chmod(restoredir, stat.S_IRWXU | stat.S_IRWXG | stat.S_IRWXO) # give new root all permissions
  os.chmod(base.temp_dir, stat.S_IRWXU | stat.S_IRWXG | stat.S_IRWXO) # and parent of new root
  before = os.stat(restoredir)
  beforeparent = os.stat(base.temp_dir)
  base.setup()
  DATE1 = subprocess.Popen(['date', '-d', '2009-08-01 21:14:21', '+%x %X'], stdout=subprocess.PIPE).communicate()[0].strip()
  DATE2 = subprocess.Popen(['date', '-d', '2009-08-01 21:14:34', '+%x %X'], stdout=subprocess.PIPE).communicate()[0].strip()
  DATE3 = subprocess.Popen(['date', '-d', '2009-08-01 21:14:41', '+%x %X'], stdout=subprocess.PIPE).communicate()[0].strip()
  base.restore_simple(restoredir, date=DATE1, backend='file', dest=(sys.path[0]+'/vols/simple'), encrypt=None)
  # A concern is that DD will overwrite the permissions of the restore directory or its parents, so check that here
  after = os.stat(restoredir)
  assert before.st_mode == after.st_mode, after.st_mode
  assert before.st_uid == after.st_uid, after.st_uid
  assert before.st_gid == after.st_gid, after.st_gid
  afterparent = os.stat(base.temp_dir)
  assert beforeparent.st_mode == afterparent.st_mode, afterparent.st_mode
  assert beforeparent.st_uid == afterparent.st_uid, afterparent.st_uid
  assert beforeparent.st_gid == afterparent.st_gid, afterparent.st_gid
  check_dir(restoredir, 'one\n')
  os.system("rm -r %s" % restoredir)
  base.restore_simple(restoredir, DATE2, encrypt=None)
  check_dir(restoredir, 'one1\n')
  os.system("rm -r %s" % restoredir)
  base.restore_simple(restoredir, DATE3, encrypt=None)
  check_dir(restoredir, 'one1!\n')

base.run(test)
