const { EmbedBuilder } = require('discord.js');
const fs = require('fs').promises;
const { spawn } = require("child_process");

module.exports = {
  name: "short-url",
  description: "Shortens a URL using small.ssh.surf",
  options: [{
    "name": "url",
    "description": "The URL that you want shorter",
    "required": true,
    "type": 3 // 6 is type USER
  }],
  run: async (client, interaction) => {
    let rand = Math.floor(Math.random() * 99999).toString();
    let URL = interaction.options._hoistedOptions[0].value;
    var dir = '/var/www/html/short/' + rand;

    const content = "<?php\nheader(\"Location: " + URL + "\")\n?>";

    console.log(content);

    try {
      const stats = await fs.stat(dir);
      if (!stats.isDirectory()) {
        throw new Error(`${dir} is not a directory`);
      }
    } catch (error) {
      if (error.code === 'ENOENT') {
        console.log(`${dir} does not exist`);
      } else {
        throw error;
      }
      await fs.mkdir(dir);
      console.log(`Created: ${dir}`);
      await fs.writeFile(`${dir}/index.php`, content);
      console.log(`Wrote ${dir}/index.php`);

      const chown = spawn("chown", ["-R", "www-data:www-data", `/var/www/html/short/${rand}`]);
      chown.on("exit", (code) => {
        console.error(`chown exited with code ${code}`);
      });
      chown.stdout.on("data", (data) => {
        console.log(`chown stdout: ${data}`);
      });
      chown.stderr.on("data", (data) => {
        console.error(`chown stderr: ${data}`);
      });
      chown.on("error", (error) => {
        console.error(`chown error: ${error.message}`);
      });
      const embed = new EmbedBuilder()
        .setColor("#FF0000")
        .setTitle("The URL has been shrunk!")
        .setDescription(`https://short.ssh.surf/${rand}`)
        .setTimestamp()
        .setFooter({ text: `Requested by ${interaction.user.tag}`, iconURL: `${interaction.user.displayAvatarURL()}` });
      interaction.followUp({ embeds: [embed] });
      rand = Math.floor(Math.random() * 99999).toString();
    }
  },
};
