#! /usr/bin/env ruby

# Ugly code for checkpoint 1
# To use the script: ./checkpoint1.rb Group#, e.g. ./checkpoint1.rb 20
# If you think there is something missing in the script, email xil@cs.cmu.edu 
# Xi Liu


if ARGV.size == 0
	puts "Usage: ./checkpoint1.rb Group# (e.g. ./checkpoint1.rb 20)"
	exit
else
begin
	groupno = Integer(ARGV[0])
rescue
	puts "The group number must be an integer!"
	exit
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
if (system "mkdir " + pathtmp) == false
	puts "Cannot create temporary directory. Email xil@cs.cmu.edu about this problem."
	exit
end

# Checkout the checkpoint 1
reponame  = "P1Group" + 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/svn/" + reponame + "/tags/checkpoint1 --username " + reponame
if system(syscall) == false
	puts "Sorry, you didn't pass checkpoint 1: Did you check in tag/checkpoint1?"
	system "rm -rf " + pathtmp
	exit
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 
	puts "Sorry, you didn't pass checkpoint 1: Failed to make!"
	system "rm -rf " + pathtmp
	exit
end

# make successful, check if sircd is built
if File.exist?(filename)
        puts "Congrats! You passed checkpoint 1."
else
        puts "Sorry, you didn't pass checkpoint 1: Did you name executable sircd?"
end

# delete the temporary directory
system "rm -rf " + pathtmp 
