#!/usr/bin/python
# stringreplace.py: Replace text in .mo files
# Stringmodding Scripts for Maemo 5
# Thomas Perl <thp.io/about>; 2011-02-07

import subprocess
import os
import sys

if len(sys.argv) != 4:
    print 'usage: %s /path/to/file.mo "search" "replace"' % (sys.argv[0],)
    sys.exit(1)

filename, search, replace = sys.argv[1:]
outname = os.path.basename(filename)

unfmt = subprocess.Popen(['msgunfmt', filename], stdout=subprocess.PIPE)
fmt = subprocess.Popen(['msgfmt', '-', '-o', outname], stdin=subprocess.PIPE)

for line in unfmt.stdout:
    xline = line.replace(search, replace)
    if line != xline:
        print 'replacing:', line, 'with:     ', xline, \
              '='*(max(len(xline),len(line))+10)
    fmt.stdin.write(xline)

unfmt.wait()
fmt.stdin.close()
fmt.wait()

print 'output file written to:', outname

