#!/usr/bin/env python3

import cgitb

cgitb.enable()

from github import Github
g = Github("726616947299f1cf6afb24221f2663b90eeaf050")

import sys
import os
import json
import subprocess

import struct, fcntl, os
import time

wwwroot="/var/www/git-readonly"

def addHook(name):
  pr = os.path.join(wwwroot,name+".git/hooks/post-receive")
  template = os.path.join(wwwroot,"trac-post-recieve.py")
  if os.path.exists(pr) and (os.path.getmtime(pr) > os.path.getmtime(template)):
    return
  data = open(template,"r").read().replace("@REPONAME@", name)
  f = open(pr+".tmp","w")
  f.write(data)
  f.close()
  os.rename(pr+".tmp", pr)
  subprocess.call(["chmod", "u+x", pr])
  print("Installed hook: " + pr)

f = open("/tmp/OpenModelica-github.lock", "w")
b = True
while b:
  try:
    fcntl.lockf(f, fcntl.LOCK_EX | fcntl.LOCK_NB)
    b = False
  except IOError:
    b = True
    time.sleep(10)

if not os.path.isdir(wwwroot):
  os.makedirs(wwwroot)

try:
  updated = False
  for repo in g.get_user("OpenModelica").get_repos():
    gitdir = os.path.join(wwwroot,repo.name+".git")
    pushed_at=str(repo.pushed_at)
    try:
      needsupdate = open(gitdir+".last_update").read().strip(" \n") != pushed_at.strip(" \n")
    except:
      needsupdate = True
    if not os.path.isdir(gitdir):
      print("Init %s" % repo.name)
      sys.stdout.flush()
      assert(0==subprocess.call(["git", "init", "--bare", gitdir + ".tmp"]))
      os.chdir(gitdir + ".tmp")
      assert(0==subprocess.call(["git", "config", "--bool", "html.receivepack", "false", repo.clone_url]))
      assert(0==subprocess.call(["git", "remote", "add", "--mirror=fetch", "origin", repo.clone_url]))
      needsupdate = True
      os.chdir(wwwroot)
      os.rename(gitdir + ".tmp", gitdir)
    addHook(repo.name)
    if needsupdate:
      os.chdir(gitdir)
      print("Updating %s" % repo.name)
      assert(0==subprocess.call(["git", "remote", "set-url", "origin", repo.clone_url]))
      sys.stdout.flush()
      assert(0==subprocess.call(["git", "remote", "update","--prune"]))
      updated = True
    else:
      continue
    open(gitdir + ".last_update", "w").write(pushed_at)
  #if updated:
  #  assert(0==subprocess.call(["wget", "--quiet", "-O", "/dev/null", "https://test.openmodelica.org/hudson/job/OpenModelica_MAKE_NEW_COMMIT/build?token=abcopenmodelicaxyz&cause=Triggered+by+github&delay=15"]))
  #  print("Triggered OpenModelica_MAKE_NEW_COMMIT")
except Exception as e:
  print(e)
  raise
print("All OK")
