class Kitsune::Kit::Commands::SetupDoMetrics

def create

def create
  unless Kitsune::Kit::Defaults.metrics[:enable_do_metrics]
    say "โš ๏ธ DigitalOcean Metrics Agent setup is disabled via ENABLE_DO_METRICS=false", :yellow
    return
  end
  filled_options = Kitsune::Kit::OptionsBuilder.build(
    options,
    required: [:server_ip],
    defaults: Kitsune::Kit::Defaults.ssh
  )
  with_ssh(filled_options) do |ssh|
    install_agent(ssh)
  end
end

def install_agent(ssh)

def install_agent(ssh)
  marker = "/usr/local/backups/setup_do_metrics.after"
  script = <<~BASH
    set -e
    sudo mkdir -p /usr/local/backups
    if [ -f "#{marker}" ]; then
      echo "๐Ÿ” Metrics Agent already installed, skipping."
      exit 0
    fi
    echo "โœ๐Ÿป Installing DigitalOcean Metrics Agent..."
    curl -sSL https://repos.insights.digitalocean.com/install.sh | sudo bash
    sudo touch "#{marker}"
    echo "โœ… Metrics Agent installed"
    ps aux | grep do-agent | grep -v grep || echo "โš ๏ธ do-agent process not found"
  BASH
  say ssh.exec!(script)
end

def rollback

def rollback
  filled_options = Kitsune::Kit::OptionsBuilder.build(
    options,
    required: [:server_ip],
    defaults: Kitsune::Kit::Defaults.ssh
  )
  with_ssh(filled_options) do |ssh|
    uninstall_agent(ssh)
  end
end

def uninstall_agent(ssh)

def uninstall_agent(ssh)
  marker = "/usr/local/backups/setup_do_metrics.after"
  script = <<~BASH
    set -e
    if [ ! -f "#{marker}" ]; then
      echo "๐Ÿ’ก No marker for metrics agent found. Skipping rollback."
      exit 0
    fi
    echo "๐Ÿงน Uninstalling DigitalOcean Metrics Agent..."
    if dpkg -l | grep -q do-agent; then
      echo "๐Ÿ“ฆ Removing do-agent package..."
      sudo apt-get remove --purge -y do-agent
    else
      echo "๐Ÿ’ก do-agent is not installed, skipping package removal."
    fi
    if systemctl list-unit-files | grep -q do-agent.service; then
      echo "โœ๐Ÿป Stopping do-agent service..."
      sudo systemctl stop do-agent || true
      sudo systemctl disable do-agent || true
    else
      echo "๐Ÿ’ก do-agent.service not found in systemd, skipping stop/disable"
    fi
    sudo rm -f "#{marker}"
    echo "โœ… Metrics Agent removed"
  BASH
  say ssh.exec!(script)
end

def with_ssh(filled_options)

def with_ssh(filled_options)
  Net::SSH.start(
    filled_options[:server_ip],
    "deploy",
    port: filled_options[:ssh_port],
    keys: [File.expand_path(filled_options[:ssh_key_path])],
    non_interactive: true,
    timeout: 5
  ) do |ssh|
    yield ssh
  end
end