require 'pathname'
require 'nomansland'
require 'tty-which'

module Spior
  module Tor
    class Info
      attr_accessor :dns, :uid, :trans_port, :virt_addr

      def initialize
        @systemctl = Helpers::Exec.new("systemctl")
        @dns = search_dns
        @uid = search_uid
        @trans_port = search_trans_port
        @virt_addr = search_virt_addr
      end

      private 

      def check_deps
        Spior::Copy.new.save
        add_torrc
        Spior::Service.start
      end

      def self.grep?(file, regex)
        is_found = false
        return is_found if ! File.exist? file
        File.open(file) do |f|
          f.each do |line|
            is_found = true if line.match(regex)
          end
        end
        is_found
      end

      def add_torrc
        user = 'User tor'
        pid = ''
        dir = 'DataDirectory /var/lib/tor'

        case Nomansland::distro?
        when :gentoo
          pid = 'PIDFile /run/tor/tor.pid'
          dir = 'DataDirectory /var/lib/tor/data'
        when :debian
          user = 'debian-tor'
        when :ubuntu
          user = 'debian-tor'
        end

        string = <<EOF
# Generated by Spior
#{user}
#{pid}
#{dir}
GeoIPExcludeUnknown 1
DNSPort 127.0.0.1:9061
AutomapHostsOnResolve 1
AutomapHostsSuffixes .exit,.onion
SocksPort 9050
VirtualAddrNetworkIPv4 10.192.0.0/10
TransPort 9040 IsolateClientAddr IsolateClientProtocol IsolateDestAddr IsolateDestPort
TestSocks 1
MaxCircuitDirtiness 600
EOF
        new_file = Helpers::NewFile.new(string, "torrc", "/etc/tor")
        new_file.add
        new_file.perm("root", "644")
      end

      def search_dns
        9061
      end

      def search_uid
        case Nomansland::distro?
        when :debian
          `id -u debian-tor`.chomp
        when :ubuntu
          `id -u debian-tor`.chomp
        else
          `id -u tor`.chomp
        end
      end

      def search_trans_port
        9040
      end

      def search_virt_addr
        "10.192.0.0/10"
      end
    end
  end
end
