#!/usr/bin/python

import fnmatch
import os
import sys
import re
from StringIO import StringIO


if len(sys.argv) == 3:
    print("Using name and uid from args")
    user =  sys.argv[1]
    group = sys.argv[2]
else:
    print("Using .env")
    import ConfigParser
    config = ConfigParser.ConfigParser()
    with open(".env") as stream:
        stream = StringIO("[.env]\n" + stream.read())  # This line does the trick.
        config.readfp(stream)

    user = config.get('.env', 'DOCKER_USER')
    group = config.get('.env', 'DOCKER_GROUP')


matches = []
for root, dirnames, filenames in os.walk('./docker'):
    for filename in fnmatch.filter(filenames, 'Dockerfile.dist'):
        matches.append(os.path.join(root, filename))

for dist in matches:
    with open(dist, 'r') as f:
        all = f.read()
        #  if root remove add user
        if  user == 'root':
            all = re.sub('RUN groupadd(.*)\n', "", all)
        all = all.replace('$user$', user).replace('$uid$', group)
        with open(dist.replace('.dist', ''), 'w') as df:
            df.write(all)