/*
* 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
    //**************************************************************************
    String revision
    List<String> popLocations
    Date date

    /**
     *
     */
    // accurev pop [-H <host>] -O -R -t <date|revision> -v <stream name> -L <output directory> <elements>
    public void execute() {
        boolean error = false
        
        // authenticate if not currently logged in
        this.login();
        
        try {
            // update workspace to specified revision/date
            def popCommand = [scmCommand, 'pop', '-O', '-R']; // populate recursive with overwriting
            if (host) {
                popCommand << '-H' << host
            }
            if (revision) {
                popCommand << '-t' << revision;
            }
            else if (date) {
                popCommand << '-t' << scmHelper.formatDate(date);
            }
            else {
                println "Neither revision nor date specified for checkout"
            }
            
            popCommand << '-v' << streamName              // the stream to populate from
            popCommand << '-L' << directory.absolutePath; // location to populate, must be used with -v flag
            
            if (popLocations && popLocations.size() > 0) {
                popCommand << "-D"
                for (String path : popLocations) {
                    popCommand << path
                }
            }
            else {
                popCommand << '.'                         // all elements in the stream
            }
            cmdHelper.runCommand('Populate', popCommand)
        }
        catch (ExitCodeException e) {
            println e.getMessage()
            error = true
        }
        finally {
            this.logout()
            
            if (error) {
                System.exit(1)
            }
        }
    }
}