///|
#derive(Debug, Eq)
pub(all) enum ProbeMode {
  Disabled
  Auto
  Banner
  Http
  Https
}

///|
#derive(Debug)
pub struct ServiceInfo {
  protocol : String
  banner : String?
  http_status : Int32?
  title : String?
  server : String?
  location : String?
  certificate_der_base64 : String?
  certificate : CertificateInfo?
  certificate_error : String?
  truncated : Bool
}

///|
fn service(protocol : String) -> ServiceInfo {
  {
    protocol,
    banner: None,
    http_status: None,
    title: None,
    server: None,
    location: None,
    certificate_der_base64: None,
    certificate: None,
    certificate_error: None,
    truncated: false,
  }
}

///|
fn parse_banner(bytes : BytesView, truncated : Bool) -> ServiceInfo {
  let text = @utf8.decode_lossy(bytes)
  let first = text.split("\n").next().unwrap_or("").trim().to_owned()
  let protocol = if first.has_prefix("SSH-2.0-") ||
    first.has_prefix("SSH-1.99-") {
    "ssh"
  } else if first.has_prefix("HTTP/1.") {
    "http"
  } else {
    "unknown"
  }
  { ..service(protocol), banner: Some(first), truncated, }
}

///|
async fn probe_connection(
  socket : @socket.Tcp,
  target : String,
  address : @socket.Addr,
  mode : ProbeMode,
  timeout_ms : Int32,
  max_bytes : Int32,
  cert_verify : Bool,
  cert_ca_file : String?,
  openssl : String,
) -> (ServiceInfo?, String?) {
  let mut found : ServiceInfo? = None
  let failure = try {
    @async.with_timeout(timeout_ms, () => {
      let secure = mode == Https ||
        (mode == Auto && address.port.to_int() is (443 | 8443 | 9443))
      let send_http = mode == Http ||
        secure ||
        (
          mode == Auto &&
          address.port.to_int() is (80 | 8000 | 8008 | 8080 | 8081 | 8888)
        )
      if send_http {
        let request = @utf8.encode(
          "GET / HTTP/1.0\r\nHost: \{target}:\{address.port}\r\nUser-Agent: mscan/0.1\r\nAccept: text/html\r\nConnection: close\r\n\r\n",
        )
        if secure {
          let tls = @tls.Tls::client(
            socket,
            host=target,
            trust=NoVerification,
            require_shutdown=false,
          )
          defer tls.close()
          let cert = tls.get_peer_certificate()
          let certificate = match cert {
            Some(cert) => {
              guard cert.length() <= 65536 else {
                raise InputError("certificate exceeds 64 KiB")
              }
              Some(@base64.encode(cert))
            }
            None => None
          }
          found = Some({
            ..service("tls"),
            certificate_der_base64: certificate,
          })
          let mut details = None
          let mut certificate_error = None
          if cert is Some(der) {
            try
              inspect_certificate(
                der,
                target,
                verify=cert_verify,
                ca_file?=cert_ca_file,
                openssl~,
              )
            catch {
              err => certificate_error = Some(err.to_string())
            } noraise {
              info => details = Some(info)
            }
          }
          found = Some({
            ..service("tls"),
            certificate_der_base64: certificate,
            certificate: details,
            certificate_error,
          })
          tls.write(request)
          let response = read_http(tls, max_bytes, on_data=bytes => {
            try
              http_info(
                bytes,
                true,
                bytes.length() == max_bytes,
                max_decoded_bytes=max_bytes,
                cancelled=@async.is_being_cancelled,
              )
            catch {
              _ => {
                let head = http_head(bytes) catch { _ => None }
                if head is Some(head) {
                  found = Some({
                    ..http_evidence(head, true),
                    certificate_der_base64: certificate,
                    certificate: details,
                    certificate_error,
                  })
                }
              }
            } noraise {
              info =>
                found = Some({
                  ..info,
                  certificate_der_base64: certificate,
                  certificate: details,
                  certificate_error,
                })
            }
          })
          found = Some({
            ..http_info(
              response,
              true,
              response.length() == max_bytes,
              max_decoded_bytes=max_bytes,
              cancelled=@async.is_being_cancelled,
            ),
            certificate_der_base64: certificate,
            certificate: details,
            certificate_error,
          })
        } else {
          socket.write(request)
          let response = read_http(socket, max_bytes, on_data=bytes => {
            try
              http_info(
                bytes,
                false,
                bytes.length() == max_bytes,
                max_decoded_bytes=max_bytes,
                cancelled=@async.is_being_cancelled,
              )
            catch {
              _ => {
                let head = http_head(bytes) catch { _ => None }
                if head is Some(head) {
                  found = Some(http_evidence(head, false))
                }
              }
            } noraise {
              info => found = Some(info)
            }
          })
          found = Some(
            http_info(
              response,
              false,
              response.length() == max_bytes,
              max_decoded_bytes=max_bytes,
              cancelled=@async.is_being_cancelled,
            ),
          )
        }
      } else {
        let buffer = FixedArray::make(max_bytes, b'\x00')
        let mut used = 0
        while used < max_bytes {
          let count = socket.read_into(buffer.mut_view(start=used))
          if count == 0 {
            break
          }
          used += count
          let bytes = Bytes::from_array(buffer[:used].to_owned())
          found = Some(parse_banner(bytes, used == max_bytes))
          if bytes.iter().any(b => b == b'\n') {
            break
          }
        }
      }
    })
    None
  } catch {
    err => Some(err.to_string())
  }
  (found, failure)
}

///|
fn ascii_lower(text : StringView) -> String {
  let output = StringBuilder()
  for c in text {
    output.write_char(
      if c is ('A'..<='Z') {
        (c.to_int() + 32).unsafe_to_char()
      } else {
        c
      },
    )
  }
  output.to_string()
}