# -*- coding: iso-8859-13
import time
import os

def inplace_change(filename, pairs):
  # Safely read the input filename using 'with'
  with open(filename) as f:
    s = f.read()

  # Safely write the changed content, if found in the file
  with open(filename, 'w') as f:
    for p in pairs:
      s = s.replace(p[0], p[1])
    f.write(s)

# font choice
font = 'https://fonts.googleapis.com/css?family=Cardo'

print 'Replacing strings in html files ...'

# replacements in English version

pairs = [('&lt;no title&gt; &mdash; m21s.tk', 'm21s.tk'),
         ('&lt;no title&gt;', 'm21s.tk'),
	 ('../../_static/custom.css', font),
	 ('../_static/custom.css', font),
	 ('_static/custom.css', font),
	 ('m21s.tk/blog', 'm21s.tk/en/blog')]

matches = []
for root, dirnames, filenames in os.walk('website/en'):
    for filename in filenames:
      if filename.endswith('.html'):
	matches.append(os.path.join(root, filename))

for filename in matches:
  print 'Processing', filename
  inplace_change (filename, pairs)

inplace_change ('website/en/searchindex.js', [('&lt;no title&gt;', 'm21s.tk')])

# replacements in Polish version

pairs = [('&lt;no title&gt; &mdash; m21s.tk', 'm21s.tk'),
         ('&lt;no title&gt;', 'm21s.tk'),
         ('Archives', 'Archiwum'),
         ('Tags', 'Etykiety'),
         ('Posts tagged', 'Wpisy z etykietą'),
         ('Posts by', 'Wpisy podpisane'),
         ('Author', 'Autor'),
         ('Tag', 'Etykieta'),
         ('Posted in', 'Wpisy z'),
         ('Next', 'Następny'),
         ('Previous', 'Poprzedni'),
	 ('Szybkie wyszukiwanie', 'Wyszukiwanie'),
	 ('Read more', 'Czytaj dalej'),
	 ('../../_static/custom.css', font),
	 ('../_static/custom.css', font),
	 ('_static/custom.css', font),
	 ('getElementsByEtykietaName', 'getElementsByTagName'), # fix Tag --> Etykieta in this case (JavaScript)
	 ('m21s.tk/blog', 'm21s.tk/pl/blog'),
         ('Comments', 'Komentarze')]

matches = []
for root, dirnames, filenames in os.walk('website/pl'):
    for filename in filenames:
      if filename.endswith('.html'):
	matches.append(os.path.join(root, filename))

for filename in matches:
  print 'Processing', filename
  inplace_change (filename, pairs)

inplace_change ('website/pl/searchindex.js', [('&lt;no title&gt;', 'm21s.tk')])
