'use strict';

const fs = require('fs');
const cp = require('child_process');
const join = require('path').join;
const mkdirp = require('mkdirp');

const options = require('./options');

console.log('Checking main directories');

if (missing(options.repo)) {
    mkdirp.sync(options.repo);
    console.log(options.repo + ' created');
}

if (missing(options.out)) {
    mkdirp.sync(options.out);
    console.log(options.out + ' created');
}

console.log('Checking visualizer clones');

if (missing(options.head) || missing(join(options.head, '.git'))) {
    cp.execFileSync('git', ['clone', 'https://github.com/NPellet/visualizer.git', 'head'], {
        cwd: options.repo
    });
    console.log('Cloned visualizer-head');
}

if (missing(options.build) || missing(join(options.build, '.git'))) {
    cp.execFileSync('git', ['clone', 'head', 'build'], {
        cwd: options.repo
    });
    console.log('Cloned visualizer-build');
}

console.log('Checking symbolic links');

createSymlinkIfMissing('HEAD', options.head);
createSymlinkIfMissing('src', options.head);
createSymlinkIfMissing('head', options.head);

createSymlinkIfMissing('testcase', join(options.head, 'testcase'));
createSymlinkIfMissing('doc', join(options.head, 'doc'));

createSymlinkIfMissing('min', join(options.out, 'HEAD-min'));
createSymlinkIfMissing('build', join(options.out, 'HEAD-min'));

function missing(dir) {
    try {
        fs.accessSync(dir);
        return false;
    } catch (e) {
        return true;
    }
}

function createSymlinkIfMissing(name, target) {
    let symlink = join(options.out, name);
    let stat;
    try {
        stat = fs.lstatSync(symlink);
    } catch (e) {
        return fs.symlinkSync(target, symlink);
    }
    if (!stat.isSymbolicLink()) {
        throw new Error('There is already a file named ' + symlink);
    }
}

@@ -964,24 +964,67 @@
 c links');%0A%0A
+const headSrc = join(options.head, 'src');%0A
 createSymlin
@@ -1042,28 +1042,23 @@
 'HEAD', 
-options.
 head
+Src
 );%0Acreat
@@ -1082,28 +1082,23 @@
 ('src', 
-options.
 head
+Src
 );%0Acreat
@@ -1123,28 +1123,23 @@
 'head', 
-options.
 head
+Src
 );%0A%0Acrea

fix head symlinks