<commit_before>// @flow

/* ::
import type MariaSQL from 'mariasql';
*/

const harborClient = require('../../clients/harborClient');
const logger = require('../../logger');
const R = require('ramda');
const Sql = require('../env-variables/sql');
const PSql = require('./sql');
const { isPatchEmpty, prepare, query, whereAnd } = require('../../util/db');

const lagoonHarborRoute = R.compose(
  R.defaultTo('http://172.17.0.1:8084'),
  R.find(R.test(/harbor-nginx/)),
  R.split(','),
  R.propOr('', 'LAGOON_ROUTES'),
)(process.env);

const lagoonWebhookAddress = R.compose(
  R.defaultTo('http://webhook-handler:3000'),
  R.find(R.test(/webhook-handler/)),
  R.split(','),
  R.propOr('', 'LAGOON_ROUTES'),
)(process.env);

async function createHarborProject(sqlClient /* : MariaSQL */, harborClient /* : harborClient */, lagoonProjectName /* : string */) {
  // Returns an empty string on an error and a string on a success

  // Create harbor project
  try {
    var res = await harborClient.post(`projects`, {
      body: {
        count_limit: -1,
        project_name: lagoonProjectName,
        storage_limit: -1,
        metadata: {
          auto_scan: "true",
          reuse_sys_cve_whitelist: "true",
          public: "false"
        }
      }
    });
    logger.debug(`Harbor project ${lagoonProjectName} created!`)
  } catch (err) {
    if (err.statusCode == 409) {
      // 409 means project already exists
      logger.info(`Unable to create the harbor project "${lagoonProjectName}", as it already exists in harbor!`)
    } else {
      logger.error(`Unable to create the harbor project "${lagoonProjectName}", error: ${err}`)
      return ""
    }
  }

  // Get new harbor project's id
  try {
    const res = await harborClient.get(`projects?name=${lagoonProjectName}`)
    var harborProjectID = res.body[0].project_id
    logger.debug(`Harbor project id for ${lagoonProjectName} is: ${harborProjectID}`)
  } catch (err) {
    if (err.statusCode == 404) {
      logger.error(`Unable to get the harbor project id of "${lagoonProjectName}", as it does not exist in harbor!`)
      return
    } else {
      logger.error(`Unable to get the harbor project id of "${lagoonProjectName}" !!`)
      return ""
    }
  }
  return harborProjectID
}

async function createRobot(sqlClient /* : MariaSQL */, harborClient /* : harborClient */, lagoonProjectName /* : string */, harborProjectID /* : string */, robot /* : string */) {
  // Returns false on an error and a token object on a success

  // Create robot account for new harbor project
  try {
    const timestamp = Math.floor(Date.now() / 1000)
    var robotName = (robot != "") ? robot : `${lagoonProjectName}-${timestamp}`

    const res = await harborClient.post(`projects/${harborProjectID}/robots`, {
      body: {
        name: robotName,
        access: [
          {
            resource: `/project/${harborProjectID}/repository`,
            action: "push"
          }
        ]
      }
    })
    var harborTokenInfo = res.body
    logger.debug(`Robot ${robotName} was created for Harbor project ${lagoonProjectName} !`)
  } catch (err) {
    // 409 means project already exists
    // 201 means project created successfully
    if (err.statusCode == 409) {
      logger.warn(`Unable to create a robot account for harbor project "${lagoonProjectName}", as a robot account of the same name already exists!`)
    } else {
      logger.error(`Unable to create a robot account for harbor project "${lagoonProjectName}"!`, err)
      return false
    }
  }
  return harborTokenInfo
}

async function removeRobot(sqlClient /* : MariaSQL */, harborClient /* : harborClient */, lagoonProjectName /* : string */, harborProjectID /* : string */, robotName /* : string */) {
  // Returns false on an error and true on a success

  // Check for preexisting robot account of the same name
  var robots = []
  try {
    const res = await harborClient.get(`projects/${harborProjectID}/robots`);

    for (var i = 0; i < res.body.length; i++) {
      if (res.body[i].name == `robot\$${robotName}`) {
        robots.push(res.body[i])
      }
    }
  } catch (err) {
    logger.info(`Unable to retrieve list of current robot accounts for Harbor Project: ${lagoonProjectName}`, err)
  }

  // Remove preexisting robot account
  try {
    for (var i = 0; i < robotNames.length; i++) {
      var result = await harborClient.delete(`projects/${harborProjectID}/robots/${robots[i].id}`, {
        body: {
          project_id: harborProjectID,
          robot_id: robots[i].id
        }
      });
      logger.debug(`Removed harbor robot account: ${robots[i].name}`)
    }
  } catch (err) {
    logger.error(`Unable to remove pre-existing robot accounts for Harbor project: ${lagoonProjectName}`, err)
    return false
  }
  return true
}

async function removeAllRobots(sqlClient /* : MariaSQL */, harborClient /* : harborClient */, lagoonProjectName /* : string */, harborProjectID /* : string */) {
  // Returns false on an error and true on a success

  // Check for preexisting robot account of the same name
  var robots = []
  try {
    const res = await harborClient.get(`projects/${harborProjectID}/robots`);

    for (var i = 0; i < res.body.length; i++) {
      robots.push(res.body[i])
    }
  } catch (err) {
    logger.info(`Unable to retrieve list of current robot accounts for Harbor Project: ${lagoonProjectName}`, err)
  }

  // Remove preexisting robot account
  try {
    for (var i = 0; i < robotNames.length; i++) {
      var result = await harborClient.delete(`projects/${harborProjectID}/robots/${robots[i].id}`, {
        body: {
          project_id: harborProjectID,
          robot_id: robots[i].id
        }
      });
      logger.debug(`Removed harbor robot account: ${robots[i].name}`)
    }
  } catch (err) {
    logger.error(`Unable to remove pre-existing robot accounts for Harbor project: ${lagoonProjectName}`, err)
    return false
  }
  return true
}

async function removeHarborEnvVars(sqlClient /* : MariaSQL */, lagoonProjectName /* : string */) {
  // Returns false on an error and true on a success

  // Find any currently set env vars
  var old_env_vars = [];
  try {
    const result = await query(
      sqlClient,
      PSql.selectProjectByName(lagoonProjectName),
    );
    const env_vars = await query(
      sqlClient,
      `SELECT *<commit_msg>Removing unused 'removeRobot' and 'removeAllRobots' functions<commit_after>// @flow

/* ::
import type MariaSQL from 'mariasql';
*/

const harborClient = require('../../clients/harborClient');
const logger = require('../../logger');
const R = require('ramda');
const Sql = require('../env-variables/sql');
const PSql = require('./sql');
const { isPatchEmpty, prepare, query, whereAnd } = require('../../util/db');

const lagoonHarborRoute = R.compose(
  R.defaultTo('http://172.17.0.1:8084'),
  R.find(R.test(/harbor-nginx/)),
  R.split(','),
  R.propOr('', 'LAGOON_ROUTES'),
)(process.env);

const lagoonWebhookAddress = R.compose(
  R.defaultTo('http://webhook-handler:3000'),
  R.find(R.test(/webhook-handler/)),
  R.split(','),
  R.propOr('', 'LAGOON_ROUTES'),
)(process.env);

async function createHarborProject(sqlClient /* : MariaSQL */, harborClient /* : harborClient */, lagoonProjectName /* : string */) {
  // Returns an empty string on an error and a string on a success

  // Create harbor project
  try {
    var res = await harborClient.post(`projects`, {
      body: {
        count_limit: -1,
        project_name: lagoonProjectName,
        storage_limit: -1,
        metadata: {
          auto_scan: "true",
          reuse_sys_cve_whitelist: "true",
          public: "false"
        }
      }
    });
    logger.debug(`Harbor project ${lagoonProjectName} created!`)
  } catch (err) {
    if (err.statusCode == 409) {
      // 409 means project already exists
      logger.info(`Unable to create the harbor project "${lagoonProjectName}", as it already exists in harbor!`)
    } else {
      logger.error(`Unable to create the harbor project "${lagoonProjectName}", error: ${err}`)
      return ""
    }
  }

  // Get new harbor project's id
  try {
    const res = await harborClient.get(`projects?name=${lagoonProjectName}`)
    var harborProjectID = res.body[0].project_id
    logger.debug(`Harbor project id for ${lagoonProjectName} is: ${harborProjectID}`)
  } catch (err) {
    if (err.statusCode == 404) {
      logger.error(`Unable to get the harbor project id of "${lagoonProjectName}", as it does not exist in harbor!`)
      return
    } else {
      logger.error(`Unable to get the harbor project id of "${lagoonProjectName}" !!`)
      return ""
    }
  }
  return harborProjectID
}

async function createRobot(sqlClient /* : MariaSQL */, harborClient /* : harborClient */, lagoonProjectName /* : string */, harborProjectID /* : string */, robot /* : string */) {
  // Returns false on an error and a token object on a success

  // Create robot account for new harbor project
  try {
    const timestamp = Math.floor(Date.now() / 1000)
    var robotName = (robot != "") ? robot : `${lagoonProjectName}-${timestamp}`

    const res = await harborClient.post(`projects/${harborProjectID}/robots`, {
      body: {
        name: robotName,
        access: [
          {
            resource: `/project/${harborProjectID}/repository`,
            action: "push"
          }
        ]
      }
    })
    var harborTokenInfo = res.body
    logger.debug(`Robot ${robotName} was created for Harbor project ${lagoonProjectName} !`)
  } catch (err) {
    // 409 means project already exists
    // 201 means project created successfully
    if (err.statusCode == 409) {
      logger.warn(`Unable to create a robot account for harbor project "${lagoonProjectName}", as a robot account of the same name already exists!`)
    } else {
      logger.error(`Unable to create a robot account for harbor project "${lagoonProjectName}"!`, err)
      return false
    }
  }
  return harborTokenInfo
}

async function removeHarborEnvVars(sqlClient /* : MariaSQL */, lagoonProjectName /* : string */) {
  // Returns false on an error and true on a success

  // Find any currently set env vars
  var old_env_vars = [];
  try {
    const result = await query(
      sqlClient,
      PSql.selectProjectByName(lagoonProjectName),
    );
    const env_vars = await query(
      sqlClient,
      `SELECT *
{'fraction_non_alphanumeric': 0.13946530257697135, 'fraction_numerical': 0.008107325547727053, 'mean_word_length': 2.925, 'pattern_counts': {'":': 0, '<': 7, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 2, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '669429', 'n_tokens_mistral': 3238, 'n_tokens_neox': 3055, 'n_words': 882}