#include <gtest/gtest.h>

#include <stdint.h>

#include <adb.h>
#include <proca.h>

using namespace std;

/**
 * @brief Run system command
 * @param [in] cmd Command to run
 * @param [in] show_log Print debug information ot not
 * @return true if success
 */
static bool RunCommand(const string& cmd, bool show_log=false);

static const int kDaemonKillingRepeatNumber = 5;
static const size_t kDaemonStartingThreshold = 10;
static const size_t kDeviceRebootThreshold = 90;

static bool RunCommand(const string& cmd, bool show_log) {
  if (show_log) {
    cout << "Running cmd: '" << cmd << "'" << endl;
  }

  string run_cmd = cmd;
  if (!show_log) {
    run_cmd += " &> /dev/null";
  }

  return Adb::Shell(run_cmd.c_str()) == 0 ? true : false;
}

TEST(DaemonTest, 01_PaDaemonIsStartedAfterKilling) {
  for (int i = 0; i < kDaemonKillingRepeatNumber; ++i) {
    ASSERT_TRUE(Proca::KillDaemon()) << "PA daemon can not be killed";

    bool is_run = Proca::WaitForDaemon(kDaemonStartingThreshold);
    ASSERT_TRUE(is_run) << "PA daemon is NOT started after killing for " << kDaemonStartingThreshold << " seconds";

    sleep(1);

    ASSERT_TRUE(RunCommand("canary")) << "Canary SHOULD be passed";
  }
}

TEST(DaemonTest, 02_PaDaemonIsStartedAfterReboot) {
  ASSERT_EQ(Adb::Shell("reboot"), 0) << "Device can not be rebooted";

  sleep(kDeviceRebootThreshold);

  bool is_run = Proca::WaitForDaemon(20);
  ASSERT_TRUE(is_run) << "PA daemon is NOT started after rebooting";
}
