#!/usr/bin/env ruby # vim: filetype=ruby require 'conoha' require 'conoha/util' require 'pp' subcommand = ARGV.shift Conoha.init! def server_id(server_id_or_index) if server_id_or_index.length == '01234567-89ab-cdef-0123-456789abcdef'.length server_id_or_index else Conoha.vps_list[server_id_or_index.to_i] end end def image_ref_or_name(str) if str.length == '01234567-89ab-cdef-0123-456789abcdef'.length str else x = Conoha.images.find { |e| e[0] == str } if x.nil? STDERR.puts "There is no image the name \"#{str}\"." exit 1 end x[1] end end case subcommand when 'version', '--version', '-v' puts ConohaVersion::ITSELF when 'authenticate' Conoha.authenticate! puts 'Succeeded!' when 'vpslist' pp Conoha.vps_list when 'ipaddress' exit 1 if ARGV.size != 1 pp Conoha.ip_address_of server_id(ARGV.first) when 'create' pp Conoha.create *ARGV when 'delete' exit 1 if ARGV.size != 1 puts Conoha.delete server_id(ARGV.first) when 'boot' exit 1 if ARGV.size != 1 puts Conoha.boot server_id(ARGV.first) when 'shutdown' exit 1 if ARGV.size != 1 puts Conoha.shutdown server_id(ARGV.first) when 'imagelist' pp Conoha.images when 'imagecreate' exit 1 if ARGV.size != 2 name = ARGV[1] puts Conoha.create_image server_id(ARGV[0]), name when 'imagedelete' exit 1 if ARGV.size != 1 image_ref = image_ref_or_name ARGV.first puts Conoha.delete_image image_ref when 'createfromimage', 'restore' exit 1 if ARGV.size < 1 image_ref = image_ref_or_name ARGV[0] ram = ARGV[1] || 'g-1gb' puts Conoha.create_from_image image_ref, ram when 'ssh' exit 1 if ARGV.size < 1 || 2 < ARGV.size ipaddress = ipv4(Conoha.ip_address_of(server_id(ARGV.first))) user = ARGV[1].nil? ? '' : "#{ARGV[1]}@" command = "ssh -oStrictHostKeyChecking=no #{user}#{ipaddress}" puts command system command when 'mosh' exit 1 if ARGV.size != 1 ipaddress = ipv4(Conoha.ip_address_of(server_id(ARGV.first))) command = "mosh #{ipaddress}" puts command system command when 'browse' exit 1 if ARGV.size < 1 || 2 < ARGV.size ipaddress = ipv4(Conoha.ip_address_of(server_id(ARGV.first))) port = ARGV[1].nil? ? '' : ":#{ARGV[1]}" command = "xdg-open http://#{ipaddress}#{port}" puts command system command when 'dump' exit 1 if ARGV.size != 2 server_id_cache = server_id(ARGV[0]) puts "conoha shutdown #{server_id_cache}" Conoha.shutdown server_id_cache name = ARGV[1] loop do sleep 60 puts "conoha imagecreate #{server_id_cache} #{name}" result = Conoha.create_image server_id_cache, name break if result == 'OK' puts '# Error! Retry after 60 seconds...' end puts '# OK!' loop do sleep 60 puts "conoha delete #{server_id_cache}" result = Conoha.delete server_id_cache break if result == 'OK' puts '# Error! Retry after 60 seconds...' end puts '# OK!' else STDERR.puts 'Error' end