#!/usr/bin/env python3

import os
import re
import tempfile

def parse_env_file(fname):
    envs = {}
    env_reg = re.compile('^(?:\s*export)?\s*(.*)\s*=\s*(.*)\s*$')

    with open(fname, 'r') as f:
        for line in f:
            if '=' not in line:
                continue

            m = env_reg.match(line)
            envs[m.group(1)] = m.group(2)

    return envs

def mutilate_figure_name(fig_fname, envs):
    return fig_fname

if __name__ == "__main__":
    from argparse import ArgumentParser

    parser = ArgumentParser()
    #parser.add_argument('-f', '--figures', nargs='*')
    parser.add_argument("-d", "--directories", nargs='*')
    parser.add_argument('out_dir', default='./figures', type=str)

    args = parser.parse_args()

    os.makedirs(args.out_dir, exist_ok=True)

    #with open(args.out_file, 'w') as fp:
    if True:
        for d in args.directories:
            d = os.path.realpath(d)
            fig_dir = os.path.join(d, 'figures')
            env_fname = os.path.join(d, 'env.sh')

            if not os.path.exists(fig_dir):
                print(f"Cannot find {fig_dir}")
                continue

            ## parse properties from env.sh
            #envs = parse_env_file(env_fname)
            #print(envs, fig_dir)

            for f in os.listdir(fig_dir):
                fname, ext = os.path.splitext(f)

                dname = os.path.basename(d)

                if ext not in ['.pdf', '.png']:
                    continue

                link_name = fname + "_" + dname + ext

                target = os.path.realpath(os.path.join(fig_dir, f))
                tmpLink = tempfile.mktemp(dir=args.out_dir)

                os.symlink(target, tmpLink)
                os.rename(tmpLink, os.path.join(args.out_dir, link_name))


