module Flydata
  module Command
    class Setup < Base
      LOG_PATH_EXAMPLES=
        %w(/var/log/httpd/access_log /var/log/apache2/access.log
           /var/log/httpd-access.log /var/log/apache2/access_log
           /var/log/messages /var/log/maillog /var/log/mysql/error.log
           /home/*/deploy/shared/log/*.log)
      OTHER = '-- None of above --'

      # readline settings for asking log path
      Readline.completion_append_character = "/"
      Readline.completion_proc = Proc.new do |str|
        Dir[str+'*'].grep( /^#{Regexp.escape(str)}/ )
      end

      def run
        # login
        Flydata::Command::Login.new.run unless flydata.credentials.authenticated?

        begin
          path = choose_log_path_from_examples
          case path
          when OTHER; ask_log_path
          else; create_log_entry(path, ask_log_deletion)
          end
          newline
        end while more_entry?

        # start client process
        sender = Flydata::Command::Sender.new
        sender.start
      end

      private
      def choose_log_path_from_examples
        candidates = (`ls #{LOG_PATH_EXAMPLES.join(' ')} 2>/dev/null`).split(/\s+/)
        candidates << OTHER
        choice = nil
        say('Please select your log path for sending FlyData')
        newline
        choose do |menu|
          menu.index = :letter
          menu.index_suffix = ") "
          menu.prompt = "Your log path:  "
          menu.choices(*candidates) {|item| choice = item}
        end
        newline
        choice
      end
      def ask_log_path
        path = nil
        loop do
          path = Readline.readline("Enter the absolute path of your log (return to cancel):  ")
          return if path.empty?
          break if FileTest.file?(path) and FileTest.readable?(path)
          say(" ! #{path} is not a readable file!")
          newline
        end
        create_log_entry(path, ask_log_deletion)
      end
      def ask_log_deletion
        say("** Log deletion setting **")
        say("Flydata has a log deletion feature that flydata will delete old log archives uploaded by flydata automatically.")
        say("Flydata will delete logs whose last modified timestamp is 7 days ago.")
        ask_yes_no("Set auto log deletion mode?")
      end
      def create_log_entry(path, log_deletion)
        data_port = flydata.data_port.get
        flydata.data_entry.create(data_port_id: data_port['id'], log_path: path, log_deletion: log_deletion)
        Flydata::Command::Crontab.new.run if log_deletion
        say("Process successfuly!") if flydata.response.code == 200
      end
      def more_entry?
        ask_yes_no("Do you want to add more log path?")
      end
    end
  end
end