/*
* 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 java.text.*;
import java.util.Date;

public class SCMCheckout extends SCMStep {

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

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

    Date date;

    /**
     *
     */
    public void execute() {
        initWorkspace();

        CommandHelper cmdHelper = getCommandHelperBase();

        // Convert date into revision
        if (!revision && date) {
            String dateString = getDateArgumentFormatter().format(date);
            revision = lookupRevision(date);
            println "Translated '$dateString' into $revision";
        }

        // switch off of branch to avoid `fatal: Cannot force update the current branch.`
        def coCmd = [scmCommand, '--no-pager', 'checkout', '--force', '--quiet', revision ?: getRemoteTrackingBranch()]
        cmdHelper.runCommand('Git Checkout', coCmd)

        // create branch from the specified start point
        def branchCommand = [scmCommand, '--no-pager', 'branch', '--force', branch]
        if (revision) {
            branchCommand << revision
        }
        else {
            branchCommand << '--track' << getRemoteTrackingBranch();
        }
        cmdHelper.runCommand('Git Branch', branchCommand)

        def checkoutCommand = [scmCommand, '--no-pager', 'checkout', '--force', branch]
        cmdHelper.runCommand('Git Checkout', checkoutCommand)

        // translate symbolic revisions into sha1
        if (!revision || !(revision ==~ /[0-9a-fA-F]{40}/)) {
            def revisionCommand = [scmCommand, '--no-pager', 'rev-parse', '--verify', 'HEAD'];
            revision = getCommandText(revisionCommand);
            println("Using revision $revision");
        }
    }
}