#!/usr/bin/python
#####################################################################
#
#			pyWeather
#			Ver 0.1b
#			Scripted by Groundhog[@linuxfreak.com]
#			-pyWeather grabs weather info for the given METAR and then 
#			  fowards it through SMTP to given email  -- Ideal for Cron
#  
#####################################################################

from ftplib import *
import rfc822, string, smtplib, os, getpass
from sys import *

# BETA !!! - Future will bring command line argments for this - Right now just mod.

# Pre-execution variable inits.
noaa_url = "weather.noaa.gov"
metar_dir = "/data/observations/metar/decoded/"
mail_from = "pyWeather@localhost"

user = getpass.getuser() 
if user == 'root':
	tmp = "/root/.pyweatherdat"
else: 
	tmp = "/home/" + user + "/.pyweatherdat"



#Some name crap -- gotta make sure they know who wrote this
print "\n\t\t\tpyWeather\n\t\t\tVer. 0.1b\n\t\t\tby GroundHog[@linuxfreak.com]\n\t\t\t6.30.99\n\nVisit www.nws.noaa.gov/oso/oso1/oso12/metar.htm for METAR ID's for your area.\n" 


#Variable initiation
#-Catch command line fubar's
try:
	metar = argv[1]
	foward_mail = argv[2]		# (@localhost !!!)
	smtp_serv = argv[3]
	mail_sub = "pyWeather Updates for " + metar + "\n"
	metar = metar + ".TXT"
	weather = mail_sub + '\n'
except IndexError:
	print "Usage: pyWeather.py [METAR] [FOWARD EMAIL ADDRESS] [SMTP SERVER]"
	sys.exit()

#Random data init's
if os.path.exists(tmp) == 1:
	os.remove(tmp)

data = open(tmp,'w')

if smtp_serv == 'localhost':
	smpt_serv = '127.0.0.1'


# FTP Sh-ite
ftp = FTP(noaa_url)
ftp.login()            
ftp.cwd(metar_dir)
ftp.retrbinary('RETR ' + metar, data.write)
ftp.quit

data.close()

report = open(tmp, 'r')
weather = weather + report.read()
weather = weather + "\npyWeather - Ver .01b\nQuestion's/Comments/Sugestions Groundhog@linuxfreak.com\n" 


# Mail Crappola
toaddrs  = string.splitfields(foward_mail, ',')		# RFC822 conformacy
server = smtplib.SMTP(smtp_serv)
server.sendmail(mail_from, toaddrs, weather)
server.quit()