import os
import subprocess

from django.conf import settings
from django.core.management.base import BaseCommand

from scrutiny.projects.models import Module


class Command(BaseCommand):
    help = 'Create checkouts of modules'

    def handle(self, verbosity, *args, **options):
        self.verbose = int(verbosity) > 1
        checkouts_directory = os.path.join(settings.MEDIA_ROOT, 'src')
        if not os.path.exists(checkouts_directory):
            os.mkdir(checkouts_directory)

        for module in Module.objects.all():
            if not module.repository_url:
                continue

            checkout_dir = os.path.join(checkouts_directory, module.name)

            if not os.path.exists(checkout_dir):
                # full clone
                cmd = ['git', 'clone', module.repository_url, module.name]
                cwd = checkouts_directory
            else:
                # pull
                cmd = ['git', 'pull', '--ff-only']
                cwd = checkout_dir

            if self.verbose:
                print('- ' + module.name)
            subprocess.run(cmd, capture_output=not (self.verbose), cwd=cwd, check=True)
