# /usr/bin/python
# coding: utf-8
import sys
import os
import shutil
import re
import datetime
import pytz
 
#ディレクトリへのパス
logDirPath = '/ログのディレクトリパス/'
 
#正規表現
#パスにマッチ
fileNamePtn = '(access|error)_log\.[0-9]{8}$'
 
#ファイル名にマッチ
fileName_ptn = '.*fileName.*(access|error)_log\.[0-9]{8}$'
 
#access_logにマッチさせる
accsNamePtn = 'access_log\.[0-9]{8}$'
#error_logにマッチさせる
errNamePtn = 'error_log\.[0-9]{8}$'
 
#アクセスログ内のUTC時刻マッチ
#例:[22/May/2018:08:21:01 +0000]
accs_ptn = '[0-9]{2}/\D{3}/[0-9]{4}:[0-9]{2}:[0-9]{2}:[0-9]{2}\s\+[0-9]{4}'
 
#実はJST⁇の行のチェック
accs_ptn_jst = '[0-9]{2}/\D{3}/[0-9]{4}:[0-9]{2}:[0-9]{2}:[0-9]{2}\s\+0900'
 
#エラーログの時刻にマッチ
#例:[Tue Jun 07 15:34:25.126709 2670]
error_ptn = '\D{3}\s\D{3}\s[0-9]{2}\s[0-9]{2}:[0-9]{2}:[0-9]{2}\.[0-9]{6}\s2[0-9]{3}'
 
def changeJST(string):
    result = ""
    jst_time = ""
    #もしJST時刻ならスルー
    if re.search(accs_ptn_jst, string):
      return None
    #アクセスログにマッチ
    elif re.search(accs_ptn, string):
      ff = re.search(accs_ptn, string)
      utc = []
      #月
      ffDec = re.search('/\D{3}', ff.group(0))
      utc.append(ffDec.group(0)[1:])
      #日
      ffDec = re.search('[0-9]{2}', ff.group(0))
      utc.append(ffDec.group(0))
      #時間
      ffDec = re.search(':[0-9]{2}:[0-9]{2}:[0-9]{2}', ff.group(0))
      utc.append(ffDec.group(0)[1:])
      #時差
      ffDec = re.search('\+[0-9]{4}', ff.group(0))
      utc.append(ffDec.group(0))
      #年
      ffDec = re.search('2[0-9]{3}', ff.group(0))
      utc.append(ffDec.group(0))
      #並べ替え
      #形式:Nov 29 06:08:08 +0000 2006
      result = "%s %s %s %s %s" % (utc[0], utc[1], utc[2], utc[3], utc[4])
      utcDate = datetime.datetime.strptime(result, '%b %d %H:%M:%S +0000 %Y')
      jstTimezone = pytz.timezone('Asia/Tokyo')
      #Asia/Tokyoへ変換後、元のログフォーマットへ戻す
      jst_time = jstTimezone.fromutc(utcDate)
      #形式[07/Jun/2018:01:47:12 +0900]
      jst_time = jst_time.strftime('%d/%b/%Y:%X %z')
      return jst_time
    #エラーログにマッチ
    elif re.search(error_ptn, string):
      ff = re.search(error_ptn, string)
      utc = []
      #曜日
      ffDec = re.search('^\D{3}\s', ff.group(0))
      utc.append(ffDec.group(0)[:-1])
      #月
      ffDec = re.search('\s\D{3}\s', ff.group(0))
      utc.append(ffDec.group(0)[1:][:-1])
      #日
      ffDec = re.search('\s[0-9]{2}\s', ff.group(0))
      utc.append(ffDec.group(0)[1:][:-1])
      #時間
      ffDec = re.search('\s[0-9]{2}:[0-9]{2}:[0-9]{2}', ff.group(0))
      utc.append(ffDec.group(0)[1:])
      #id
      ffDec = re.search('\.[0-9]{6}', ff.group(0))
      utc.append(ffDec.group(0))
      #年
      ffDec = re.search('\s2[0-9]{3}', ff.group(0))
      utc.append(ffDec.group(0)[1:])
      
      #エラーログにマッチ
      #配列の中身の例:['Thu', 'Jun', '07', '06:35:13', '.378829', '2018']
      #並べ替え
      #形式:Nov 29 06:08:08 +0000 2006
      result = "%s %s %s +0000 %s" % (utc[1], utc[2], utc[3], utc[5])
      utcDate = datetime.datetime.strptime(result, '%b %d %H:%M:%S +0000 %Y')
      jstTimezone = pytz.timezone('Asia/Tokyo')
      #Asia/Tokyoへ変換後、元のログフォーマットへ戻す
      jst_error = jstTimezone.fromutc(utcDate)
      #形式:[Tue Jun 05 07:44:15.465239 2018]
      #Thu Jun 07 15:35:13 2018
      jst_time = jst_error.strftime('%a %b %d ')
      jst_time += jst_error.strftime('%X')
      jst_time += utc[4]
      jst_time += jst_error.strftime(' %Y')
      return jst_time
    else:
        return None
 
#標準入力から読込
for line in sys.stdin:    
    #オリジナルログの保存ディレクトリの作成
    #保存ディレクトリの存在チェック後、存在しなければmkdir
    if os.path.isdir("%sfileName" % logDirPath) is not True:
     os.makedirs("%sfileName" % logDirPath)
    #行末の改行を削除
    line = line.rstrip()
    #Readでオープン
    file = open(line, "r")
    newFileName = ""
    #念のためファイルの存在チェック後、
    #読み込んだファイルを保存ディレクトリへ移動
    if os.path.exists(line):
      fileName = re.search(fileNamePtn, line)
      fName = fileName.group(0)
      if re.search(fileName_ptn, line):
        fPath = "%sfileName/%s" % (logDirPath, fName)
        shutil.move(line, fPath)
 
      #読み込んだファイルを1行ずつ処理
      for row in file:
        #UTCからJSTへ変換する関数。JSTに変換された日付の文字列が返ってくる
        toJst = changeJST(row)
        utcToJst = ""
        if toJst is not None:
          if re.search(accsNamePtn, line):
            utcToJst = re.sub(accs_ptn, toJst, row)
          elif re.search(errNamePtn, line):
            utcToJst = re.sub(error_ptn, toJst, row)
          #新規ファイルへの書き込み。無限ループ回避の名前変更
          newFileName = line + ".log"
          newfile = open(newFileName, "a")
          newfile.write(utcToJst)
          newfile.close()
    file.close()
    #元のファイル名へ戻す
    if os.path.isfile(newFileName):      
      os.rename(newFileName, line)
    else:
      #ファイル全体で修正が無かったときに保存ディレクトリにmvしたファイルを戻す
      if re.search(fileName_ptn, line):
        fPath = "%sfileName/%s" % (logDirPath, fName)
        shutil.copy2(fPath, line)