#!/usr/bin/python
# -*- coding: utf-8 -*-
import os.path
import logging
import traceback
import sys
import os


def change_encoding(target_dir, from_encoding, dest_dir, dest_encoding):
    if not(os.path.exists(target_dir) and os.path.isdir(target_dir)):
        return
    if not(os.path.exists(dest_dir) and os.path.isdir(dest_dir)):
        return

    # make dirs in target dir
    for root, dirs, files in os.walk(target_dir):
        for directory in dirs:
            mkdir_path = dest_dir + "/" + os.path.join(root, directory).replace(target_dir, '')
            if not(os.path.exists(mkdir_path)):
                os.mkdir()

    for root, dirs, files in os.walk(target_dir):
        for file_name in files:
            before_file_path = os.path.join(root, file_name)
            after_file_path = dest_dir + before_file_path.replace(target_dir, '')

            print(after_file_path)

            text_data = ''
            with open(before_file_path, 'r', encoding=from_encoding) as rf:
                text_data = rf.read()

            with open(after_file_path, 'w', encoding=dest_encoding) as wf:
                wf.write(text_data)

if __name__ == "__main__":
    try:
        if len(sys.argv) > 4:
            change_encoding(sys.argv[1], sys.argv[2], sys.argv[3], sys.argv[4])
    except Exception as e:
        logging.error(e)
        logging.error(traceback.format_exc())