/*
* Licensed Materials - Property of IBM Corp.
* IBM UrbanCode Build
* (c) Copyright IBM Corporation 2012, 2014. All Rights Reserved.
*
* U.S. Government Users Restricted Rights - Use, duplication or disclosure restricted by
* GSA ADP Schedule Contract with IBM Corp.
*/
package com.urbancode.air.plugin.scm

import com.urbancode.air.*
import com.urbancode.air.plugin.scm.changelog.*;
import java.util.regex.Matcher

public class MercurialWorkspace {

    //**************************************************************************
    // CLASS
    //**************************************************************************

    //**************************************************************************
    // INSTANCE
    //**************************************************************************

    String hgCmd = "hg"
    File directory
    String remoteUrl
    String remoteUser
    String remotePass
    String branch
    String revision

    /**
     * Initialize the mercurial workspace with data from the remote repository
     */
    public void init() {

        // create the repository directory if not present
        if (!directory.canonicalFile.mkdirs() && !directory.exists()) {
            throw new Exception("Could not create working directory ${directory}")
        }
        else if (directory.isFile()) {
            throw new Exception("Specified working directory is a file!! ${directory}")
        }

        final def cmdHelper = new CommandHelper(directory);

        // Embed username and password credentials on remoteUrl
        if (remoteUser) {
            if (remoteUrl.startsWith('http')) {
                def userinfo = remoteUser;
                if (remotePass) {
                    userinfo += ":$remotePass"
                }
                remoteUrl = remoteUrl.replaceFirst(~'^https?://', '$0'+Matcher.quoteReplacement(userinfo)+'@')
            }
            else {
                println "warning: can not use username/password with non-http(s) url"
            }
        }

        // Repository does not exist, clone from remote
        if (!new File(directory, '.hg').isDirectory()) {
            def cloneCommand = [hgCmd, 'clone']
            if (revision) {
                cloneCommand << '-u'
                cloneCommand << revision
            }
            else if (branch) {
                cloneCommand << '--branch'
                cloneCommand << branch
            }
            else {
                cloneCommand << '--noupdate'
            }
            cloneCommand << remoteUrl
            cloneCommand << directory.absolutePath

            cmdHelper.runCommand('Mercurial Clone', cloneCommand)
        }
        // Repository already exists, fetch updates from remote
        else {
            def pullCommand = [hgCmd, 'pull']
            if (revision) {
                pullCommand << '--rev'
                pullCommand << revision
            }
            else if (branch) {
                pullCommand << '--branch'
                pullCommand << branch
            }
            pullCommand << remoteUrl
            cmdHelper.runCommand('Mercurial Pull', pullCommand)
        }
    }

    /**
     * Completely delete all files within workspace as well as the repository
     */
    public void delete() {
        if (directory.isDirectory()) {
            println "Cleaning directory $directory"
            new AntBuilder().delete(includeemptydirs:'true'){fileset(dir: directory.path, includes:'**/*', defaultexcludes:'false')}
        }
    }

//    /**
//     * Remove all untracked and all ignored files from the workspace
//     */
//    public void clean() {
//        // hg purge --all
//    }
}