#!/usr/bin/python
import re
import os
from shutil import copy

isimg = re.compile(r'(jpg|jpeg|gif|png|bmp)$', re.I).search
fromdir = [os.path.expanduser('~/../Documents/erosaku/cache'),
           os.path.expanduser('~/fuk/backup/sakura/srv/saku/cache')]
todir = os.path.expanduser('~/fuk/img/shinGETsu')

if not os.path.isdir(todir):
    os.makedirs(todir)
exists = []
for root, dirs, files in os.walk(todir):
    for f in files:
        exists.append(f)

def subdirs(dirlist):
    for dir in dirlist:
        for subdir in dirlist:
            for sd in os.listdir(subdir):
                yield os.path.join(dir, subdir, sd, 'attach')

for d in subdirs(fromdir):
    if not os.path.isdir(d):
        continue
    for f in os.listdir(d):
        frompath = os.path.join(d, f)
        if re.search(r'^s\d+_[0-9a-f+]{32}[.]\d+x\d+[.][^.]+$', f):
            continue
        found = re.search(r'^\d+_([0-9a-f]{32})\.([^.]+)$', f)
        if found:
            f = '%sx.%s' % (found.group(1)[:8], found.group(2))
        topath = os.path.join(todir, f)
        if isimg(frompath) and (f not in exists):
            print f
            copy(frompath, topath)
