#!/usr/bin/env python3

from os import chdir, mkdir
from os.path import exists, expanduser
from pathlib import Path
from shlex import split
from subprocess import check_output, run

from requests import get


def clone_apps():
    home = expanduser("~/")
    clones = Path(f"{home}/.abra/apps").absolute()
    if not exists(clones):
        mkdir(clones)

    response = get("https://git.autonomic.zone/api/v1/orgs/coop-cloud/repos")
    repos = [[p["name"], p["ssh_url"]] for p in response.json()]
    for name, url in repos:
        try:
            run(split(f"git clone {url} {clones}/{name}"))
            chdir(f"{clones}/{name}")
            if not check_output("git branch --list | wc -l", shell=True):
                run(split("git checkout main"))
        except Exception:
            pass


def main():
    clone_apps()


if __name__ == "__main__":
    main()