# -*- coding: utf-8 -*-
import pwd
from os.path import dirname, abspath, join, isdir, islink, realpath
from shutil import rmtree
from os import makedirs, stat
from glob import glob

import pathvnc
from scribe import login

TEST_DIR = dirname(abspath(__file__))
TMP_DIR = join(TEST_DIR, 'tmp')

def test_ftpdir():
    OLD_DIR = login.HOME_PATH
    login.HOME_PATH = TMP_DIR
    ftpdir = join(TMP_DIR, '.ftp')
    if isdir(TMP_DIR):
        rmtree(TMP_DIR)
    makedirs(TMP_DIR)
    try:
        info=pwd.getpwnam('eole')
    except:
        info=pwd.getpwnam('scribe')
    uid = info.pw_uid
    homedir = TMP_DIR
    shares = [{'name': 'test1', 'path': '/home/test1'},
            {'name': 'test2', 'path': '/home/test2'}]
    login.gen_ftpdir(uid, homedir, shares)
    dirnames = []
    ori_dirnames = []
    for name in ['test2', 'perso', 'test1']:
        dirnames.append(join(ftpdir, name))
        ori_dirnames.append(join(TMP_DIR, name))
    assert glob(join(ftpdir, '*')).sort() == dirnames.sort()
    assert stat(ftpdir).st_mode == 16704
    assert stat(ftpdir).st_uid == uid
    assert stat(ftpdir).st_gid == 0
    # les répertoires d'origine n'existant pas, les liens symboliques ne sont pas créés
    for dirname in dirnames:
        assert not islink(dirname)
    # on créé les répertoires d'origine
    for dirname in ori_dirnames:
        makedirs(dirname)

    # regénère les liens
    login.gen_ftpdir(uid, homedir, shares)
    # les liens symboliques doivent maintenant exister
    for dirname in dirnames:
        assert islink(dirname)
    assert realpath(join(ftpdir, 'test2')) == join(TMP_DIR, 'test2')
    assert realpath(join(ftpdir, 'test1')) == join(TMP_DIR, 'test1')
    assert realpath(join(ftpdir, 'perso')) == join(TMP_DIR, 'perso')
    login.HOME_PATH = OLD_DIR
