#!/usr/bin/env python

import cgitb

cgitb.enable()

import sys
import os
import urllib2
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:
  response = urllib2.urlopen('https://api.github.com/users/OpenModelica/repos')
  updated = False
  for repo in json.load(response):
    gitdir = os.path.join(wwwroot,repo["name"]+".git")
    try:
      needsupdate = open(gitdir+".last_update").read().strip(" \n") != repo['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", "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"])
      sys.stdout.flush()
      assert(0==subprocess.call(["git", "remote", "update","--prune"]))
      updated = True
    else:
      continue
    open(gitdir + ".last_update", "w").write(repo['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")
