#!/usr/bin/env python
#301 2022

import sys, os, time
import urllib2
import smtplib
import datetime

now=datetime.datetime.now()
cyear=now.year
cmonth=now.month
cday=now.day
now=datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
dt=datetime.datetime.strptime(now,'%Y-%m-%d %H:%M:%S')
tt=dt.timetuple()
cday_num=tt.tm_yday
tmp=datetime.datetime.strptime(str(cyear)+"-"+str(cday_num),"%Y-%j").strftime("%a %d %b %m %Y")
cweek=tmp.split()[0]

file=open('/Users/js/crons/wondermark.py','r')
line=file.readline()
line=file.readline()
file.close()
day_num=int(line.replace('#','').split()[0])
year=int(line.replace('#','').split()[1])
tmp=datetime.datetime.strptime(str(year)+"-"+str(day_num),"%Y-%j").strftime("%a %d %b %m %Y")
week=tmp.split()[0]

iflag=0
try:
  tmp=datetime.datetime.strptime(str(cyear)+"-"+str(cday_num),"%Y-%j").strftime("%a %d %b %m %Y")
  req='https://www.gocomics.com/wondermark/'+str(cyear)+'/'+ \
       str(tmp.split()[-2])+'/'+tmp.split()[1]
  time.sleep(2)
  response=urllib2.urlopen(req)
  page=response.readlines()
  lines=str(page).replace('>','\n')
  for z in lines.split('\n'):
    if 'canonical' in z:
      if req in z:
        iflag=1
        raise
except:
  pass

try:
  msg='Reply-To: no-reply@uoregon.edu\nContent-Type: text/html\n'+ \
      'Subject: Wondermark\n\n'
  msg=msg+'<html>\n'
  if iflag:
    msg=msg+'<a href="'+req+'">click me</a>'
    server=smtplib.SMTP('smtp.uoregon.edu')
    server.sendmail('your_name@uoregon.edu','your_name@gmail.com',msg)
    server.quit()

  file=open('/Users/js/crons/wondermark.py','r')
  all=file.readlines()
  file.close()
  all[1]='#'+str(cday_num)+' '+str(cyear)+'\n'
  file=open('/Users/js/crons/wondermark.py','w')
  for n in range(len(all)):
    file.write(all[n])
  file.close()

except:
  pass
