'use strict';

require('../../../universalify/index.js');
var Path = require('path');
require('../fs/index.js');
var index$2 = require('../mkdirs/index.js');
var index$3 = require('../path-exists/index.js');
var stat = require('../util/stat.js');
var index = require('../../../../_virtual/index21.js');
var index$1 = require('../../../../_virtual/index20.js');

const u = index.__exports.fromPromise;
const path = Path;
const fs = index$1.__exports;
const mkdir = index$2.mkdirs;
const { pathExists } = index$3.pathExists_1;
const { areIdentical } = stat.stat;

async function createLink (srcpath, dstpath) {
  let dstStat;
  try {
    dstStat = await fs.lstat(dstpath);
  } catch {
    // ignore error
  }

  let srcStat;
  try {
    srcStat = await fs.lstat(srcpath);
  } catch (err) {
    err.message = err.message.replace('lstat', 'ensureLink');
    throw err
  }

  if (dstStat && areIdentical(srcStat, dstStat)) return

  const dir = path.dirname(dstpath);

  const dirExists = await pathExists(dir);

  if (!dirExists) {
    await mkdir.mkdirs(dir);
  }

  await fs.link(srcpath, dstpath);
}

function createLinkSync (srcpath, dstpath) {
  let dstStat;
  try {
    dstStat = fs.lstatSync(dstpath);
  } catch {}

  try {
    const srcStat = fs.lstatSync(srcpath);
    if (dstStat && areIdentical(srcStat, dstStat)) return
  } catch (err) {
    err.message = err.message.replace('lstat', 'ensureLink');
    throw err
  }

  const dir = path.dirname(dstpath);
  const dirExists = fs.existsSync(dir);
  if (dirExists) return fs.linkSync(srcpath, dstpath)
  mkdir.mkdirsSync(dir);

  return fs.linkSync(srcpath, dstpath)
}

var link = {
  createLink: u(createLink),
  createLinkSync
};

exports.link = link;
