"""
This module provides some essential utilities for Roundabout.

Roundabout - git hosting for everyone <https://roundabout-host.com>
Copyright (C) 2023-2025 Roundabout developers <root@roundabout-host.com>

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU Affero General Public License for more details.

You should have received a copy of the GNU Affero General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.
"""

import os
import subprocess


def git_command(repo, data, *args, return_err=False, return_exit=False):
    if not os.path.isdir(repo):
        raise FileNotFoundError(f"Repo {repo} not found")
    env = os.environ.copy()

    command = ["git", *args]

    proc = subprocess.Popen(command, cwd=repo, env=env, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
                            stdin=subprocess.PIPE)

    if data:
        proc.stdin.write(data)

    out, err = proc.communicate()
    exit_code = proc.returncode

    result = (out,)

    if return_err:
        result = result + (err,)
    if return_exit:
        result = result + (exit_code,)

    return result[0] if len(result) == 1 else result

