#!/usr/bin/env ruby

# To use the script: ./checkpoint1.rb Group# Username
# e.g. ./checkpoint1.rb 20 hbovik
# If you think there is something missing, email daegunw@andrew.cmu.edu
# Daegun Won
# Originally written by Xi Liu

taemail = "nbauernfeind@cmu.edu"

if ARGV.size < 2
	puts "Usage: ./checkpoint1.rb Group# Username (e.g. ./checkpoint1.rb 20 hbovik)"
	exit 1
else
	begin
		groupno = Integer(ARGV[0])
		username = ARGV[1]
	rescue
		puts "The group number must be an integer!"
	exit 1
	end
end

# Make a temporary directory, not really thread safe, but should be because of groupno is unique
count = 0
pathtmp = "15-441-p1-cp-tmp" + groupno.to_s + "-" + count.to_s

while File.exist?(pathtmp)
	count = count+1
	pathtmp =  "15-441-p1-cp-tmp" + groupno.to_s + "-" + count.to_s
end

$pathtmp = pathtmp

if (system "mkdir " + pathtmp) == false
	puts "Cannot create temporary directory. Email " + taemail + "about this problem."
	exit 1
end

# On failure cleanup.
def cleanup(error)
	system "rm -rf " + $pathtmp
	if (error == "")
		puts "Congratulations: Checkpoint 1 passed!"
		exit 0
	else
		puts "You failed checkpoint 1: " + error
		exit 1
	end
end

# Checkout the checkpoint 1
reponame  = "Project1Team" + groupno.to_s
localpath = pathtmp + "/checkpoint1"
filename  = localpath + "/sircd"
syscallpath = "cd " + localpath + "\n"

syscall  = "cd " + pathtmp + "\nsvn co https://moo.cmcl.cs.cmu.edu/441-s10/svn/" + reponame + "/tags/checkpoint1 --username " + username

if system(syscall) == false
	cleanup "Couldn't find tagged directory: tags/checkpoint1"
end

# Delete sircd if it is there
if File.exist?(filename)
	puts "sircd is in the repo, deleting it..."
	system syscallpath + "rm -f sircd"
end

# try to make
if (system syscallpath + "make") == false 
	cleanup "Failed to make!"
end

# make successful, check if sircd is built
if not File.exist?(filename)
	cleanup "Did you name executable sircd?"
end

if not File.stat(filename).executable?
	cleanup "Created sircd file is not executable."
end

cleanup ""
