#!/usr/bin/env ruby
require 'fileutils'
require File.expand_path(File.join(File.dirname(__FILE__), '..', 'lib', 'ssh-config'))

# ssh-config - Manipulate config values in the .ssh/config file.
# 
# ssh-config help
# ssh-config dump
# ssh-config list
# ssh-config show <host-nickname>
# ssh-config search <regex>
# ssh-config set <host-nickname> <setting> <value> [<setting> <value> [...]]
#     Note: "<setting> -" deletes a setting
# ssh-config rm <host-nickname> # delete config settings for that host
# ssh-config copy <host-nickname> <new-host-nickname> # copy settings from one to the other.
# ssh-config alias <host-nickname> <alternate-host-nickname> # add an alias
# ssh-config unalias [<host-nickname>] <alias-to-remove>

config = ConfigFile.new
argv = ARGV
command = argv.shift

def usage
  str =<<HELP
ssh-config - Configure your .ssh/config file

Usage:
  ssh-config <command> <params>

Commands:
  help - show this message
  dump - parse and dump the config file
  list - list configured hosts
  show <host> - display the settings for host
  search <pattern> - search all hosts with any detail matching pattern
  set <host> <setting> <value> [<setting> <value> [...]] - set a value
    NOTE: If host does not exist, it will be created
    NOTE: If value is -, setting will be deleted, e.g. set User -
    NOTE: If all values are deleted, section will NOT be removed, use rm instead
  unset <host> <setting> - Remove a setting from a host section
  rm <host> - Remove configuration for a host
  copy <host> <newhost> - Duplicate the settings for a host
    NOTE: If Hostname contains Host, new host will be automagically updated
HELP

end

def colorize output
    # Colorize hostname and aliases
    output = output.gsub(/Host\s+([a-zA-Z0-9 ]*)/, "\033[33mHost \033[31m"+'\1'+"\033[0m")
    # Colorize comments
    output = output.gsub("#", "\033[30m#").gsub("\n", "\033[0m\n")
    # Colorize parameters
    output.gsub(/^(\s*[a-zA-Z0-9]*\s*\b)/, "\033[37m"+'\1'+"\033[0m")
end

case command
when '-?'
  puts usage
when '-h'
  puts usage
when 'help'
  puts usage
when 'list'
  puts config.list
when 'show'
  puts colorize config.show(*argv)
when 'search'
  search = argv.shift
  result = config.search(search).gsub(search, "\033[43m#{search}\033[0m")
  puts result unless result.empty?
when 'cp', 'copy'
  config.copy! argv.shift, argv.shift, *argv
when 'unset'
  config.unset!(argv.shift, *argv)
when 'set'
  config.set!(*argv)
when 'rm', 'del', 'delete'
  config.rm! argv.shift
when 'dump'
  puts colorize config.dump
when 'alias'
  config.alias!(*argv)
when 'unalias'
  config.unalias!(*argv)
else
  $stderr.puts "Sorry, don't know how to handle command '#{command}'"
end

