#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (C) 2011 Ryohei Ueda
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#     http://www.apache.org/licenses/LICENSE-2.0
# 
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import roslib; roslib.load_manifest("parallel_util")
from parallel_util import *
from optparse import OptionParser
import os
import sys

def parse_options():
    parser = OptionParser()
    parser.add_option("-i", "--input", dest = "input",
                      default = os.path.join(os.environ["HOME"],
                                             ".cssh-clusters"),
                      help = """input cssh configuration file.
it defaults to ~/.cssh-clusters""")
    parser.add_option("-u", "--user", dest = "user",
                      default = None,
                      help = """username to connect ssh""")
    parser.add_option("-g", "--group", dest = "group",
                      help = "specify the group of the cssh cluster")
    parser.add_option("-p", "--port", dest = "port",
                      default = 11311,
                      type = int,
                      help = "specify the port of roscore. (defaults to 11311)")
    parser.add_option("--timeout", dest = "timeout",
                      type = int,
                      default = None,
                      help = "specify timeout of ssh connection in sec")
    parser.add_option("-q", "--quiet", dest = "quiet",
                      action = "store_true",
                      default = False,
                      help = "run script in quiet mode")
    (options, args) = parser.parse_args()
    if not options.group:
        parser.print_help()
        sys.exit(1)
    return options

def main():
    options = parse_options()
    infos = cpuinfos(from_cssh_file = options.input,
                     cssh_group = options.group,
                     verbose = not options.quiet,
                     timeout = options.timeout,
                     ros_port = options.port,
                     username = options.user)
    if infos[1]:
        print "port %s is available" % (options.port)
    else:
        print "port %s is NOT available" % (options.port)
    launchservices = ["--launchservice='%s*%s'" % (cpuinfo[0], host)
                      for host, cpuinfo in infos[0].items()]
    print " ".join(launchservices)
    sys.exit(0)
    
if __name__ == "__main__":
    main()
