#!/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/>.

# Test whether we correctly handle full backup destinations

import sys
import os
import random
import struct
import statvfs
sys.path.insert(0, sys.path[0]+'/..')
import base
import ldtp

def makerandom(name, size):
  f = open(name, 'wb')
  
  random.seed(42)
  
  while size > 0:
    num = int(random.getrandbits(32))
    string = struct.pack('<I', num)
    f.write(string)
    size = size - 4
  
  f.close()

def full():
  dest = base.create_mount(size=1)
  base.setup()
  base.backup_simple(error='lblBackuplocationistoosmallTryusingonewithmorespace', backend='file', includes=['/bin'], dest=dest)

def deleteold():
  dest = base.create_mount(size=20)
  backupdir = base.get_temp_name('backup')
  os.makedirs(backupdir)
  manifests = []
  
  # backup of 1M
  makerandom(os.path.join(backupdir, 'one'), 1024*1024)
  base.setup()
  base.backup_simple(backend='file', includes=[backupdir], dest=dest)
  base.last_date_change('%d days ago' % (365), dest='mount') # force full
  manifests.append(base.last_manifest(dest='mount')[1])

  # backup of 2M
  makerandom(os.path.join(backupdir, 'one'), 2*1024*1024)
  base.backup_simple()
  base.last_date_change('%d days ago' % (365), dest='mount') # force full
  manifests.append(base.last_manifest(dest='mount')[1])

  # backup of 10M
  makerandom(os.path.join(backupdir, 'one'), 10*1024*1024)
  base.backup_simple()
  base.last_date_change('%d days ago' % (365), dest='mount') # force full
  manifests.append(base.last_manifest(dest='mount')[1])

  # backup of 3M
  makerandom(os.path.join(backupdir, 'one'), 3*1024*1024)
  base.backup_simple()
  base.last_date_change('%d days ago' % (365), dest='mount') # force full
  manifests.append(base.last_manifest(dest='mount')[1])

  # backup of 10M
  makerandom(os.path.join(backupdir, 'one'), 10*1024*1024)
  base.backup_simple()
  manifests.append(base.last_manifest(dest='mount')[1])

  # Now there should be just two full backups left: 3M and 10M (the last two)
  assert manifests[-2:] == base.list_manifests(dest='mount')[1], "%s vs %s" % (str(manifests), str(base.list_manifests(dest='mount')[1]))

base.run(full)
base.run(deleteold)
