import os
import glob
import shutil
from .common import run, SiteConfig


def pull_git_repo(repo: str, build_cache: str) -> None:
    '''Pulls/clones a repo into the build cache directory.'''
    if os.path.exists(f'{build_cache}/.git'):
        run(f'git -C {build_cache} pull origin')
    else: 
        run(f'git clone {repo} {build_cache}')


def copy_assets(site: SiteConfig):
    '''Copies the list of site assets from the build cache to the web root.'''
    
    # Expand any globbed expressions.
    expanded_asset_list = []
    for a in site.assets:
        expanded_asset_list.extend(
            # Assets are defined relative to the build cache; construct the full path.
            glob.glob(f'{site.build_cache}/{a.lstrip("/")}')
        )
               
    for asset in expanded_asset_list:
        
        # Construct the destination path analogous to the source path
        # but in the web root instead of the build cache.
        destination = f'{site.web_root}/{a.lstrip("/")}'

        # Delete existing files.
        shutil.rmtree(destination, ignore_errors=True)

        # Copy the asset.
        if os.path.isdir(asset):
            shutil.copytree(asset, destination)
        elif os.path.isfile(asset):
            shutil.copyfile(asset, destination)
        else:
            continue
    
    return None