# -*- coding: binary -*-

module Msf::Exploit::Remote::HTTP::Gitea::Helpers
  # Helper methods are private and should not be called by modules

  module_function

  # Returns CSRF token string for Gitea session
  #
  # @param res [Rex::Proto::Http::Response] Rex HTTP Response object
  # @return [String,nil] csrf token if found, nil otherwise
  def gitea_get_csrf(res)
    res&.get_html_document&.at('//input[@name="_csrf"]/@value')&.text
  end

  # Returns string for Gitea repository uid
  #
  # @param res [Rex::Proto::Http::Response] Rex HTTP Response object
  # @return [String,nil] repo uid string if found, nil otherwise
  def gitea_get_repo_uid(res)
    res&.get_html_document&.at('//input[@id="uid"]/@value')&.text
  end

  # Returns string for Gitea service type uri
  #
  # @param res [Rex::Proto::Http::Response] Rex HTTP Response object
  # @return [String,nil] Gitea service type uri string if found, nil otherwise
  def gitea_get_service_type_uri(res)
    res&.get_html_document&.at('//svg[@class="svg gitea-gitea"]/ancestor::a/@href')&.text
  end

  # Returns the POST data for a Gitea login request
  #
  # @param user [String] Username
  # @param pass [String] Password
  # @param csrf [String] Login csrf
  # @return [Hash] The post data for vars_post Parameter
  def gitea_helper_login_post_data(user, pass, csrf)
    {
      'user_name' => user,
      'password' => pass,
      '_csrf' => csrf
    }
  end

  # Returns the POST data for a Gitea create repository request
  #
  # @param name [String] Repository name
  # @param uid [String] Repository uid
  # @param csrf [String] Login csrf
  # @return [Hash] The post data for vars_post Parameter
  def gitea_helper_repo_create_post_data(name, uid, csrf)
    {
      'uid' => uid,
      'auto_init' => 'on',
      'readme' => 'Default',
      'repo_name' => name,
      'trust_model' => 'default',
      'default_branch' => 'master',
      '_csrf' => csrf
    }
  end

  # Returns the POST data for a Gitea remove repository request
  #
  # @param name [String] Repository path
  # @param csrf [String] Login csrf
  # @return [Hash] The post data for vars_post Parameter
  def gitea_helper_repo_remove_post_data(name, csrf)
    {
      'action' => 'delete',
      'repo_name' => name,
      '_csrf' => csrf
    }
  end

  # Returns the POST data for a Gitea migrate repository request
  #
  # @param name [String] Repository name
  # @param uid [String] Repository uid
  # @param service [String] Service id
  # @param url [String] Repository name
  # @param token [String] Repository auth token
  # @param csrf [String] Login csrf
  # @return [Hash] The post data for vars_post Parameter
  def gitea_helper_repo_migrate_post_data(name, uid, service, url, token, csrf)
    {
      'uid' => uid,
      'service' => service,
      'pull_requests' => 'on',
      'repo_name' => name,
      '_csrf' => csrf,
      'auth_token' => token,
      'clone_addr' => url
    }
  end
end
