#!/usr/bin/env python
# -*- Mode: Python; indent-tabs-mode: nil; tab-width: 2; coding: utf-8 -*-
#
# This file is part of Déjà Dup.
# © 2010 Michael Terry <mike@mterry.name>
#
# 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('file', sources=['/bin'], dest=dest)
  base.backup_simple(error='lblBackuplocationistoosmallTryusingonewithmorespace')

def deleteold():
  dest = base.create_mount(size=20)
  backupdir = base.get_temp_name('backup')
  os.makedirs(backupdir)
  
  # backup of 1M
  makerandom(os.path.join(backupdir, 'one'), 1024*1024)
  base.setup('file', sources=[backupdir], dest=dest)
  base.backup_simple()

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

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

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

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

  # Now there should be just two full backups left: 3M and 10M (the last two)
  f = os.statvfs(dest)
  free = f.f_bsize * f.f_bavail
  assert base.num_manifests(dest='mount') == 2
  assert base.num_manifests('full', dest='mount') == 2
  # In practice, the two previous backups 3M+10M tends to take about 14M and
  # the free space tends to be closer to 4M because the mount ends up being 18M
  assert 4*1000*1000 - 100*1000 <= free and free <= 4*1000*1000 + 100*1000, "Free is %i" % free

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