#!/usr/bin/python
import os
import sys
import math
import random
import sqlalchemy as sa
import subprocess
import prometheus_client
from prometheus_client import CollectorRegistry, Gauge
from prometheus_client.context_managers import Timer
from srht.config import cfg
from srht.database import DbSession
from gitsrht.types import Artifact, User, Repository
from datetime import datetime, timedelta

db = DbSession(cfg("git.sr.ht", "connection-string"))
db.init()

registry = CollectorRegistry()
tg = Gauge("gitsrht_periodic_time",
        "Time to run git.sr.ht-periodic jobs",
        ["section"],
        registry=registry)

gc_git_t = tg.labels("gc_git")
@gc_git_t.time()
def gc_git():
    repo_count = Repository.query.count()

    # *srht-periodic scripts are run every twenty minutes,
    # this gives us 504 runs over the course of a week;
    # hence, if we GC a 504th of the repository count each time,
    # on average, we will have GCd every repo around once a week.
    limit = int(math.ceil(repo_count / (7 * 24 * 60 / 20)))

    rc = Gauge("gitsrht_periodic_gc_git_count",
            "Amount of repos GCd by the gc_git job",
            registry=registry)
    ps = Gauge("gitsrht_periodic_gc_git_packsize",
            "Packfile size in the gc_git job (B)",
            ["stage"],
            registry=registry)

    repos = (Repository.query
            .offset(random.randrange(0, repo_count + 1 - limit))
            .limit(limit)).all()
    for r in repos:
        try:
            ps.labels("pre").inc(sum(map(lambda p: p.stat().st_size,
                os.scandir(os.path.join(r.path, "objects", "pack")))))

            def gc():
                subprocess.run(["git", "-C", r.path, "gc", "--quiet"],
                    stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
            gc()

            ps.labels("post").inc(sum(map(lambda p: p.stat().st_size,
                os.scandir(os.path.join(r.path, "objects", "pack")))))
            rc.inc()
        except FileNotFoundError:
            continue

gc_git()

pg_endpoint = cfg("sr.ht", "pushgateway", default=None)
if pg_endpoint:
    prometheus_client.pushadd_to_gateway(pg_endpoint,
            job="git.sr.ht", registry=registry)
