#! /usr/bin/env python

# A short script that tries to check when a mirror was last changed 
# 
#	Written by Tor Krill" <tor@krill.nu>
#
# Outputs hostname, time to access and latest change of DB
#

import gnomevfs
import time
import urllib
import re
import urlparse
import sys

if len(sys.argv)>1:
	if sys.argv[1]=="current" or sys.argv[1]=="extra" or sys.argv[1]=="community" or sys.argv[1]=="unstable":
		repo=sys.argv[1]
	else:
		print "Unknown repository"
		sys.exit(1)
else:
	repo="current"

print "Listing mirrors for: "+repo+"\n"

page=urllib.urlopen("http://cvs.archlinux.org/cgi-bin/viewcvs.cgi/*checkout*/base/pacman/"+repo+"?cvsroot=Current&only_with_tag=HEAD").read()

p=re.compile("^Server = (\S*)",re.MULTILINE)
data=p.findall(page)

print "Mirror".center(29)+"Time to fetch".center(15)+"Latest change".center(28)

for line in data:
	ur=line+"/"+repo+".db.tar.gz"
	print urlparse.urlparse(ur)[1].ljust(30),
	try:
		start=time.time()
		info=gnomevfs.get_file_info(ur)
		stop=time.time()
		df=time.gmtime(stop-start)[3:6]
				
		print "\t%s:%s:%s\t" % (
			str(df[0]).zfill(2),
			str(df[1]).zfill(2),
			str(df[2]).zfill(2)
			),
				
		if info.valid_fields & gnomevfs.FILE_INFO_FIELDS_CTIME:
			print time.ctime(info.ctime)
		elif info.valid_fields & gnomevfs.FILE_INFO_FIELDS_MTIME:
			print time.ctime(info.mtime)
		elif info.valid_fields & gnomevfs.FILE_INFO_FIELDS_ATIME:
			print time.ctime(info.atime)
		else:
			print "No time available"
	except gnomevfs.NotFoundError:
		print "File not found: "+ur
	except gnomevfs.NotADirectoryError:
		print "Invalid path: "+ur
	except gnomevfs.Error:
		print "Unknown error: "+ur
