#!/usr/bin/env node

var shell=require('shelljs');
var publishConfig=require(process.cwd()+'/publishConfig.js');

var GIT_USER=publishConfig.gitUser;
var PROJECT_USERNAME=publishConfig.projectUsername;
var PROJECT_REPONAME=publishConfig.projectReponame;
var remoteBranch='https://'+GIT_USER+'@github.com/'+PROJECT_USERNAME+'/'+PROJECT_REPONAME+'.git';

if(!shell.which('git')){
shell.echo('Sorry, this script requires git');
shell.exit(1);
}

if(shell.exec('npm run generate').code){
shell.echo('Error: generating html failed');
shell.exit(1);
}

shell.cd(__dirname);
shell.cd('..');
shell.cd('build');

if(shell.exec('git clone '+remoteBranch+' '+PROJECT_REPONAME+'-gh-pages').code!==0){
shell.echo('Error: git clone failed');
shell.exit(1);
}

shell.cd(PROJECT_REPONAME+'-gh-pages');

if(shell.exec('git checkout origin/gh-pages').code+
shell.exec('git checkout -b gh-pages').code+
shell.exec('git branch --set-upstream-to=origin/gh-pages').code!==0)
{
shell.echo('Error: Git checkout gh-pages failed');
shell.exit(1);
}

shell.exec('rm -rf *');

shell.cd('../..');

shell.cp('-R','build/'+PROJECT_REPONAME+'/*','build/'+PROJECT_REPONAME+'-gh-pages/');
shell.cd('build/'+PROJECT_REPONAME+'-gh-pages');

shell.exec('git add --all');
shell.exec('git commit -m "update website"');
if(shell.exec('git push origin gh-pages').code!==0){
shell.echo('Error: Git push failed');
shell.exit(1);
}else{
shell.echo('Website is live at: https://'+PROJECT_USERNAME+'.github.io/'+PROJECT_REPONAME+'/');
shell.exit(0);
}