#/usr/bin/env python -
from SCons.Script import DefaultEnvironment

env = DefaultEnvironment()

import os
import errno

def make_sure_path_exists(path):
    try:
        os.makedirs(path)
    except OSError as exception:
        if exception.errno != errno.EEXIST:
            raise

import subprocess

make_sure_path_exists(env.subst('$BUILDSRC_DIR'))

from datetime import datetime
import time
import string
import re

p = subprocess.Popen(['git', 'symbolic-ref', '-q', '--short', 'HEAD'], stdout=subprocess.PIPE)
BRANCH = p.stdout.readline().rstrip()
p = subprocess.Popen(['git', 'describe', '--tags', '--first-parent'], stdout=subprocess.PIPE)
RAW_VERSION = p.stdout.readline().rstrip()
s = re.search('(.*)(-.*)(-.*)',RAW_VERSION)
SHORT_VERSION = s.group(1)+' '+BRANCH
DETAILED_VERSION = string.replace(RAW_VERSION,'-',' '+BRANCH+'-',1)
p = subprocess.Popen(['git', 'config', '--local', '--get', 'remote.origin.url'], stdout=subprocess.PIPE)


try:
  s = re.search('(.*github.com:)(.*)', p.stdout.readline().rstrip())
  URL = string.replace("https://github.com/"+s.group(2), ".git", "/")

  url_text = """#define SOURCE_CODE_URL  "%s"
// Deprecated URL definition
#define FIRMWARE_URL  "%s"
""" % (URL, URL)
except Exception, e:
  url_text = ""

version_header_text = """/* This file is automatically generated by a compile time hook
 * Do not manually edit it
 * It does not get committed to the repository
 */

#define BUILD_UNIX_DATETIME %s
#define STRING_DISTRIBUTION_DATE "%s"
#define SHORT_BUILD_VERSION "%s"
#define DETAILED_BUILD_VERSION "%s"
%s""" % (int(time.time()), datetime.now().strftime('%Y-%m-%d %H:%M'),SHORT_VERSION, DETAILED_VERSION, url_text)

open(env.subst('$BUILDSRC_DIR/_Version.h'), 'w').write(version_header_text)