#!/usr/bin/env python
# [Gedit Tool]
# Shortcut=<Primary>bracketright
# Output=replace-document
# Save-files=document
# Input=document
# Languages=rpmspec
# Name=Add ChnageLog entry
# Applicability=all

import sys
import re
from datetime import datetime


class Spec:
    def __init__(self, data):
        self.data = data
        self.name = "Igor Gnatenko"
        self.email = "i.gnatenko.brain@gmail.com"
        self.version = self._get_tag("Version:")
        self.release = self._get_tag("Release:").replace("%{?dist}", "")
        self.macroses = {}
        self.date = datetime.utcnow().strftime("%a %b %m %Y")
        self._get_macroses()

    def _get_macroses(self):
        patMacro = re.compile("^%[ \t]*(define|global)")
        for line in self.data:
            if re.match(patMacro, line):
                self.macroses[line.split()[1]] = line.split()[2]


    def _get_tag(self, tag):
        for line in self.data:
            if line.startswith(tag):
                return line.split()[1]


    def _is_macrosized(self, line):
        if "%" in line:
            return True
        else:
            return False


    def parse_tag(self, tag):
        for macros in self.macroses:
            macros_formatted = "%{{{}}}".format(macros)
            if macros_formatted in tag:
                tag = tag.replace(macros_formatted, self.macroses[macros])
        return tag

    def _parse(self):
        if self._is_macrosized(self.version):
            self.version = self.parse_tag(self.version)
        if self._is_macrosized(self.release):
            self.release = self.parse_tag(self.release)
        l = len(self.data)
        patChangelog = re.compile("^%changelog")
        if any(re.match(patChangelog, l) for l in self.data):
            i = 0
            while i < l:
              if re.match("^%changelog", self.data[i]):
                  i += 1
                  if not self.data[i].endswith("- {}-{}\n".format(
                          self.version, self.release)):
                      offs = self._ins_head(i)
                      i += offs
                      if self.data[i + 1] != "\n":
                          self.data.insert(i, "\n")
                          i += 1
                  else:
                      self.data.insert(i + 1, "- \n")
                      i += 1
              i += 1
        else:
            self._ins_head()

    def _ins_head(self, pos=None):
        pos_default = pos
        if not pos:
            pos = len(self.data)
            pos_default = pos
            self.data.insert(pos, "\n")
            if self.data[pos - 1] != "\n":
                pos += 1
                self.data.insert(pos, "\n")
            pos += 1
            self.data.insert(pos, "%changelog\n")
            pos += 1
        self.data.insert(pos, "* {} {} <{}> - {}-{}\n".format(
                self.date,
                self.name, self.email,
                self.version, self.release))
        pos += 1
        self.data.insert(pos, "- \n")
        pos += 1
        return pos - pos_default

    def _out(self):
        print("".join(self.data))

    def parse_and_print(self):
        self._parse()
        self._out()

spec = Spec(sys.stdin.readlines())
spec.parse_and_print()
