#!/usr/bin/env python3
from functools import partial
from os import chdir, readlink
from pathlib import Path
from shutil import rmtree
from subprocess import run

myrun = partial(run, check=True)

TEST_DIR_NAME = 'test'

def create_test_dirs():
    remove_test_dir_if_exists()

    print("Creating test dir and test files")
    TEST_DIR.mkdir()
    FROM_DIR.mkdir()
    TO_DIR.mkdir()

    for file in 'one','two','three':
        (FROM_DIR / file).touch()


def test_link_directories():
    print("Testing linking two directories")

    cmd = ['./symgr', '-d', FROM_DIR, TO_DIR]
    print(f"Running cmd: {cmd}")
    run(cmd)

    print("Test: symlinks are created and point to the right place")
    for file in 'one','two','three':
        # ensure there is a link at TO_DIR / file pointing to FROM_DIR / file
        assert readlink(TO_DIR / file) == str((FROM_DIR / file).resolve())


def test_bless():
    print("Testing blessing a 'dotfile' from source to repo")

    original_path = (FROM_DIR / '.zshrc').resolve()
    new_location = (TO_DIR / '.zshrc').resolve()

    # original_path should be backed up and then
    # made a symlink pointing to new_location
    contents = 'contents'
    with open(original_path, 'w') as f:
        f.write(contents)

    cmd = ['./symgr', '-db', original_path, TO_DIR]
    print(f"Running cmd: {cmd}")
    run(cmd)

    print("Test: symlink is created")
    assert readlink(original_path) == str(new_location)

    print("Test: file contents match")
    assert open(original_path).read() == contents

    print("Test: bak file of original is created")
    assert len(list(FROM_DIR.glob('.zshrc.bak.20*'))) == 1


def test_symlink():
    print("Testing creating one symlink")

    frm = FROM_DIR / 'file'
    to = TO_DIR / 'symlink'

    frm.touch()
    to.touch()

    cmd = ['./symgr', '-d', frm, to]
    print(f"Running cmd: {cmd}")
    run(cmd)

    print("Test: original file is backed up")
    assert len(list(TO_DIR.glob('symlink.bak.20*'))) == 1

    print("Test: symlink is created and points to the right place")
    assert readlink(to) == str(frm.resolve())


def remove_test_dir_if_exists():
    if TEST_DIR.exists():
        print(f"Test dir {TEST_DIR} exists, removing")
        rmtree(TEST_DIR)


if __name__ == "__main__":
    chdir(Path(__file__).parent)

    TEST_DIR = Path(TEST_DIR_NAME)
    FROM_DIR = TEST_DIR / 'from'
    TO_DIR = TEST_DIR / 'to'

    create_test_dirs()
    test_link_directories()
    test_bless()
    test_symlink()
    remove_test_dir_if_exists()
