# Copyright 2013 Lukas Kemmer
#
# Licensed under the Apache License, Version 2.0 (the "License"); you
# may not use this file except in compliance with the License. You
# may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
# implied. See the License for the specific language governing
# permissions and limitations under the License.

"""Generate build_info.cpp with version constants, dates etc.

"""

import datetime
import os
from locale import getpreferredencoding
import subprocess

def _now_utc():
    return datetime.datetime.utcnow().strftime("%Y-%m-%d %H:%M UTC")

def _write_string_func( f, name, value ):
    f.write('\n')
    f.write('faint::utf8_string %s(){\n' % name)
    f.write('  return "%s";\n' % value)
    f.write('}\n')

# Fixme: Add git version-info (e.g. hash)

def run(faint_root, version):
    generated_dir = os.path.join(faint_root, "generated")
    if not os.path.exists(generated_dir):
        os.mkdir(generated_dir)

    cpp_path = os.path.join(generated_dir, "build-info.cpp")
    f = open(cpp_path, 'w')
    f.write('// Generated by %s\n' % os.path.basename(__file__))
    f.write('#include "text/utf8-string.hh"\n')
    f.write('namespace faint{\n\n')
    _write_string_func(f, 'faint_version', version)
    _write_string_func(f, 'faint_build_date', _now_utc())
    f.write('} // namespace\n')
    f.close()
    return cpp_path

def working_copy_modified(path):
    return subprocess.call('git diff --quiet %s' % path) == 1
