#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#列出~/.ssh/config主机到期时间
#自用ssh-expire-time命令python实现版本
#原始ssh-expire-time为shell脚本实现,参看:/v/bin/ssh-expire-time
import sys
import os
import re
import time

foundCount=0
allHostInfo=[]
allExpireTime=[]

def readHostsInfo(findflag,findNum=None):
    global foundCount
    global allHostInfo
    global allExpireTime
    with open(sshConfigFile,"r") as read_f:
        Tag=False
        findExpire=False
        allHostInfo=[]
        HostInfo=[]
        for num,line in enumerate(read_f.readlines(),1):
            if Tag==True and re.match(r'[ ]*Host ',line,re.I):
                Tag=False
                if findExpire==True:
                    allHostInfo.append(HostInfo)
                    findExpire=False
            if Tag==False and re.match(r'Host .*',line,re.I):
                Tag=True
                HostInfo=[]
                HostInfo.append(line)
                continue
            if Tag==True:
                if re.match(r'.*#[ ]*到期时间.*',line,re.I):
                    findExpire=True
                    if findflag=="all":                         
                        foundCount+=1
                        allExpireTime.append(line)
                    elif findflag=="m":
                        timeRegexp=time.strftime("%Y-0?%m", time.localtime())
                        if not re.match(r'.*'+timeRegexp+'[^0-9]+.*',line,re.I):
                            HostInfo=[]
                            Tag=False
                            findExpire=False
                            continue
                        else:
                            HostInfo.insert(0,line)
                            foundCount+=1
                    elif findflag=="n":
                        nowTime=time.localtime()
                        nowYear=nowTime.tm_year
                        nextMonth=nowTime.tm_mon+1
                        if nextMonth>12:
                            nextMonth=1
                            nowYear+=1
                        timeRegexp="{year}-0?{month}".format(year=nowYear,month=nextMonth)
                        if not re.match(r'.*'+timeRegexp+'[^0-9]+.*',line,re.I):
                            HostInfo=[]
                            Tag=False
                            findExpire=False
                            continue
                        else:
                            HostInfo.insert(0,line)
                            foundCount+=1
                HostInfo.append(line)
    return

def printUsage():
    print("""
    /v/bin/ssh-expire-time.py
    查询所有主机到期时间,按日期顺序排列
    参数一可附加参数 (month/m) 查看当月到期主机详情;
    参数一可附加参数 (next/n) 查看下月到期主机详情;
    参数二可指定最多列出的主机,缺省为-1,即列出全部匹配主机;
    Example:ssh-expire-time.py m 或 ssh-expire-time.py n;
    Example:ssh-expire-time.py m 2 (匹配两次,只显示到期前两个)  
    """)
    return

sshConfigFile="~/.ssh/config"
sshConfigFile=os.path.expanduser(sshConfigFile)

if len(sys.argv)<2 or (len(sys.argv)==2 and (str(sys.argv[1]).lower()=="--help" or str(sys.argv[1]).lower()=="-h")):
    printUsage()
    readHostsInfo('all')
    if len(allExpireTime)>0:
        allExpireTime.sort(key=None, reverse=False)
        for expireTime in allExpireTime:
            print(expireTime,end="")
    sys.exit(0)
elif len(sys.argv)==2:
    findflag=str(sys.argv[1]).lower()
    findNum=None
elif len(sys.argv)==3:
    findflag=str(sys.argv[1]).lower()
    findNum=int(sys.argv[2])

if not (findflag=="m" or findflag=="n"):
    print("参数错误!")
    printUsage()
    sys.exit(0)

readHostsInfo(findflag,findNum)
allHostInfo.sort()

suffixText=""
if findNum!=None and findNum<len(allHostInfo):
    allHostInfo=allHostInfo[:findNum]
    suffixText=",显示前 %d 个"%findNum

for Host in allHostInfo:
    Host.pop(0)
    print("".join(Host))

if foundCount>1:
    print("共找到主机 %s 个%s"%(foundCount,suffixText))

print("\nssh-expire-time.py执行完毕;Python版本:%s"%sys.version)