context: using System;
  using System.Collections.Generic;
  using System.Web.Http;
  using System.Linq;
  
  namespace mmria.server
  {
  	public class db_setupController: ApiController 
  	{ 
  		private string couchdb_url = null;
  		private string file_root_folder = null;
  
  
  		/*
  
  curl -X PUT http://uid:pwd@target_db_url/_users
  curl -X PUT http://uid:pwd@target_db_url/_replicator
  curl -X PUT http://uid:pwd@target_db_url/_global_changes
  curl -X PUT http://uid:pwd@target_db_url/metadata
  curl -X PUT http://uid:pwd@target_db_url/mmrds
  
  curl -vX POST http://uid:pwd@target_db_url/_replicate \
       -d '{"source":"http://uid:pwd@source_db_url/_users","target":"http://uid:pwd@target_db_url/_users"}' \
       -H "Content-Type:application/json"
   
  	 
  curl -vX POST http://uid:pwd@target_db_url/_replicate \
       -d '{"source":"http://muid:pwd@source_db_url/metadata","target":"http://uid:pwd@target_db_url/metadata"}' \
       -H "Content-Type:application/json"
  	 
  curl -vX POST http://uid:pwd@target_db_url/_replicate \
       -d '{"source":"http://uid:pwd@source_db_url","target":"http://uid:pwd@target_db_url/mmrds"}' \
       -H "Content-Type:application/json"
  	 
  
  
  
  		 */
  
  
  		public db_setupController()
  		{
  			if (bool.Parse (System.Configuration.ConfigurationManager.AppSettings ["is_environment_based"])) 
  			{
  				couchdb_url = System.Environment.GetEnvironmentVariable ("couchdb_url");
  				file_root_folder = System.Environment.GetEnvironmentVariable ("file_root_folder");
  			} 
  			else
  			{
  				couchdb_url = System.Configuration.ConfigurationManager.AppSettings ["couchdb_url"];
  				file_root_folder = System.Configuration.ConfigurationManager.AppSettings ["file_root_folder"];
  			}
  
  		}
  
  		public System.Dynamic.ExpandoObject Get
  		(
  			string p_user_name, 
  			string p_password,
  			string p_source_db
  		)
  		{
  			System.Console.WriteLine ("Recieved message.");
  			string result = null;
  			System.Dynamic.ExpandoObject json_result = null;
  			try
  			{
  
  				//"2016-06-12T13:49:24.759Z"
  				string request_string = this.get_couch_db_url() + "/metadata/2016-06-12T13:49:24.759Z";
  
  				System.Net.WebRequest request = System.Net.WebRequest.Create(new Uri(request_string));
  
  				request.PreAuthenticate = false;
  
  
  				if(this.Request.Headers.Contains("Cookie") && this.Request.Headers.GetValues("Cookie").Count() > 0)
  				{
  					string[] cookie_set = this.Request.Headers.GetValues("Cookie").First().Split(';');
  					for(int i = 0; i < cookie_set.Length; i++)
  					{
  						string[] auth_session_token = cookie_set[i].Split('=');
  						if(auth_session_token[0].Trim() == "AuthSession" && auth_session_token[1] != "null")
  						{
  							request.Headers.Add("Cookie", "AuthSession=" + auth_session_token[1]);
  							request.Headers.Add("X-CouchDB-WWW-Authenticate", auth_session_token[1]);
  							break;
  						}
  					}
  				}
  
  
  				System.Net.WebResponse response = (System.Net.HttpWebResponse)request.GetResponse();
  				System.IO.Stream dataStream = response.GetResponseStream ();
  				System.IO.StreamReader reader = new System.IO.StreamReader (dataStream);
  				result = reader.ReadToEnd ();
  
  				json_result = Newtonsoft.Json.JsonConvert.DeserializeObject<System.Dynamic.ExpandoObject>(result, new  Newtonsoft.Json.Converters.ExpandoObjectConverter());
  
  			}
  			catch(Exception ex) 
  			{
  				Console.WriteLine (ex);
  			}
  
  
  			//return result;
  			return json_result;
  		} 
  		/*
  		// GET api/values 
  		//public IEnumerable<master_record> Get() 
  		public System.Dynamic.ExpandoObject Get(string value) 
  		{ 
  			//System.Console.WriteLine ("Recieved message.");
  			string result = null;
  
  			//"2016-06-12T13:49:24.759Z"
  			string request_string = this.get_couch_db_url() + "/metadata/" + value;
  
  			System.Net.WebRequest request = System.Net.WebRequest.Create(new Uri(request_string));
  
  			request.PreAuthenticate = false;
  
  
  			if(this.Request.Headers.Contains("Cookie") && this.Request.Headers.GetValues("Cookie").Count() > 0)
  			{
  				string[] auth_session_token = this.Request.Headers.GetValues("Cookie").First().Split('=');
  				request.Headers.Add("Cookie", "AuthSession=" + auth_session_token[1]);
  				//request.Headers.Add(this.Request.Headers.GetValues("Cookie").First(), "");
  				request.Headers.Add("X-CouchDB-WWW-Authenticate", auth_session_token[1]);
  
  			}
  
  
  			System.Net.WebResponse response = (System.Net.HttpWebResponse)request.GetResponse();
  			System.IO.Stream dataStream = response.GetResponseStream ();
  			System.IO.StreamReader reader = new System.IO.StreamReader (dataStream);
  			result = reader.ReadToEnd ();
  
  			System.Dynamic.ExpandoObject json_result = Newtonsoft.Json.JsonConvert.DeserializeObject<System.Dynamic.ExpandoObject>(result, new  Newtonsoft.Json.Converters.ExpandoObjectConverter());
  
  			return json_result;
  		} */
  
  
  		// POST api/values 
  		//[Route("api/metadata")]
  		[HttpPost]
  		public mmria.common.model.couchdb.document_put_response Post() 
  		{ 
  			//bool valid_login = false;
  			mmria.common.metadata.app metadata = null;
  			string object_string = null;
  			mmria.common.model.couchdb.document_put_response result = new mmria.common.model.couchdb.document_put_response ();
  
  			try
  			{
  
  				System.IO.Stream dataStream0 = this.Request.Content.ReadAsStreamAsync().Result;
  				// Open the stream using a StreamReader for easy access.
  				//dataStream0.Seek(0, System.IO.SeekOrigin.Begin);
  				System.IO.StreamReader reader0 = new System.IO.StreamReader (dataStream0);
  				// Read the content.
  				string temp = reader0.ReadToEnd ();
  
  				metadata = Newtonsoft.Json.JsonConvert.DeserializeObject<mmria.common.metadata.app>(temp);
  				//System.Dynamic.ExpandoObject json_result = Newtonsoft.Json.JsonConvert.DeserializeObject<System.Dynamic.ExpandoObject>(result, new  Newtonsoft.Json.Converters.ExpandoObjectConverter());
  
  
  
  				//string metadata = DecodeUrlString(temp);
  			}
  			catch(Exception ex)
  			{
  				Console.WriteLine (ex);
  			}
  				try
  				{
  					Newtonsoft.Json.JsonSerializerSettings settings = new Newtonsoft.Json.JsonSerializerSettings ();
  					settings.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore;
  					object_string = Newtonsoft.Json.JsonConvert.SerializeObject(metadata, settings);
  
  					string metadata_url = this.get_couch_db_url() + "/metadata/"  + metadata._id;
  
  					System.Net.WebRequest request = System.Net.WebRequest.Create(new System.Uri(metadata_url));
  					request.Method = "PUT";
  					request.ContentType = "application/json";
  					request.ContentLength = object_string.Length;
  					request.PreAuthenticate = false;
  
  					if(this.Request.Headers.Contains("Cookie") && this.Request.Headers.GetValues("Cookie").Count() > 0)
  					{
  						string[] cookie_set = this.Request.Headers.GetValues("Cookie").First().Split(';');
  						for(int i = 0; i < cookie_set.Length; i++)
  						{
  							string[] auth_session_token = cookie_set[i].Split('=');
  							if(auth_session_token[0].Trim() == "AuthSession")
  							{
  								request.Headers.Add("Cookie", "AuthSession=" + auth_session_token[1]);
  								request.Headers.Add("X-CouchDB-WWW-Authenticate", auth_session_token[1]);
  								break;
  							}
  						}
  					}
  
  					using (System.IO.StreamWriter streamWriter = new System.IO.StreamWriter(request.GetRequestStream()))
  					{
  						try
  						{
  							streamWriter.Write(object_string);
  							streamWriter.Flush();
  							streamWriter.Close();
  
  
  							System.Net.WebResponse response = (System.Net.HttpWebResponse)request.GetResponse();
  							System.IO.Stream dataStream = response.GetResponseStream ();
  							System.IO.StreamReader reader = new System.IO.StreamReader (dataStream);
  
gt: 							string responseFromServer = reader.ReadToEnd ();