#!/usr/bin/python3 -BEsStt
"""This test collection attempts to verify that the DefaultFileSystemSink
class works as expected."""

import sys
sys.path = sys.path[1:] + ['/usr/lib/guerillabackup/lib', '/etc/guerillabackup/lib-enabled']

import hashlib
import os
import time

import guerillabackup
from guerillabackup.BackupElementMetainfo import BackupElementMetainfo

testDirName = '/tmp/gb-test-%s' % time.time()
print('Using %s for testing' % testDirName, file=sys.stderr)
os.mkdir(testDirName, 0o700)

baseDirFd = os.open(testDirName, os.O_RDONLY|os.O_DIRECTORY|os.O_NOFOLLOW)

sink = guerillabackup.DefaultFileSystemSink(
    {guerillabackup.DefaultFileSystemSink.SINK_BASEDIR_KEY: testDirName})
try:
  sinkHandle = sink.getSinkHandle('somepath/invalid')
  raise Exception('Illegal state')
except Exception as testException:
  if testException.args[0] != 'Slashes not conforming':
    raise testException

try:
  sinkHandle = sink.getSinkHandle('/somepath/invalid/')
  raise Exception('Illegal state')
except Exception as testException:
  if testException.args[0] != 'Slashes not conforming':
    raise testException

try:
  sinkHandle = sink.getSinkHandle('/somepath/../invalid')
  raise Exception('Illegal state')
except Exception as testException:
  if testException.args[0] != '. and .. forbidden':
    raise testException

try:
  sinkHandle = sink.getSinkHandle('/somepath/./invalid')
  raise Exception('Illegal state')
except Exception as testException:
  if testException.args[0] != '. and .. forbidden':
    raise testException

sinkHandle = sink.getSinkHandle('/somepath/valid')

sinkInputFd = os.open('/dev/urandom', os.O_RDONLY)
sinkTestData = os.read(sinkInputFd, 1<<16)

sinkStream = sinkHandle.getSinkStream()
digestAlgo = hashlib.sha512()

os.write(sinkStream, sinkTestData)
digestAlgo.update(sinkTestData)

metaInfo = {
    'BackupType': 'full',
    'StorageFileChecksumSha512': digestAlgo.digest(),
    'Timestamp': 1234567890}
sinkHandle.close(BackupElementMetainfo(metaInfo))
