//------------------------------------------------------------------------------
// <copyright file="FileStager.cs" company="Microsoft">
//      Copyright (c) Microsoft Corporation.  All rights reserved.
// </copyright>
// <summary>
//      wrapper routine for obtaining credentials for staging HPC Basic Profile data
// </summary>
//------------------------------------------------------------------------------

using Microsoft.Hpc.Scheduler;
using Microsoft.Hpc.Scheduler.Properties;
using System;

namespace FileStaging
{
    static class StagingCredentials
    {
        /// <summary>
        /// Obtain the credential string for the staging task. Environment variables
        /// are used to determine the job and task.
        /// </summary>
        static public string Credentials
        {
            get
            {
                string cluster = Environment.GetEnvironmentVariable("CCP_CLUSTER_NAME");
                string jobId = Environment.GetEnvironmentVariable("CCP_JOBID");
                string taskId = Environment.GetEnvironmentVariable("CCP_TASKID");

                IScheduler scheduler = GetScheduler(cluster);
               
                ISchedulerJob job = scheduler.OpenJob(ParseInt(jobId, "CCP_JOBID"));
                ISchedulerTask task = job.OpenTask(new TaskId(ParseInt(taskId, "CCP_TASKID")));

                return task.UserBlob;
            }
        }

        private static IScheduler GetScheduler(string ClusterName)
        {
            IScheduler scheduler = null;

            try
            {
                // Connect to remote HPCS 2008 cluster
                scheduler = new Scheduler();
                scheduler.Connect(ClusterName);
            }

            // Catch all exceptions, report error and rethrow exception
            catch (Exception e)
            {
                Console.Error.WriteLine("Connection to HPCS 2008 {0} failed:{1}.", ClusterName, e.Message);
                throw;
            }
            return scheduler;
        }

        static private int ParseInt(string s, string identity)
        {
            int t;
            if (int.TryParse(s, out t))
            {
                return t;
            }
            else
            {
                Console.Error.WriteLine("Unable to parse " + identity + ":" + s);
                throw new Exception("Unable to parse " + identity + ":" + s);
            }
        }
    }
}