using System;
using System.Collections.Generic;
using System.Text;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;

namespace QCertUtil
{
    class Program
    {
        static private void Help() {
            Console.WriteLine("QCertUtil - Red Hat certificate import utility");
			Console.WriteLine("Usage: QCertUtil [-s store] [-u] <certificate filename>");
			Console.WriteLine("");
			Console.WriteLine("Available stores: AddressBook, AuthRoot, CertificateAuthority, Disallowed,");
			Console.WriteLine("                  My, Root, TrustedPeople, TrustedPublisher");
        }

        static void Main(string[] args)
        {
            if (args.Length < 1)
            {
                Help();
                return;
            }

			int exitCode = 0;

			string fileName = string.Empty;
			StoreName storeName = StoreName.Root;
			StoreLocation storeLocation = StoreLocation.LocalMachine;

			int i = 0;
			while (i < args.Length)
			{
				if (args[i].StartsWith("-u"))
				{
					storeLocation = StoreLocation.CurrentUser;
				}
				else if (args[i].StartsWith("-s"))
				{
					try
					{
						storeName = (StoreName)Enum.Parse(typeof(StoreName), args[++i]);
					}
					catch (Exception)
					{
						Console.WriteLine("Unknown store name. Using {0} store.", storeName.ToString());
					}
				}
				else if (args[i].StartsWith("-"))
				{
					Console.WriteLine("Ignoring unknown command line option: {0}.", args[i]);
				}
				else
				{
					fileName = args[i];
				}

				i += 1;
			}

            try
            {
				X509Store store = new X509Store(storeName, storeLocation);
                X509Certificate2 cert = new X509Certificate2(fileName);

                store.Open(OpenFlags.ReadWrite);
                store.Add(cert);
                store.Close();
            }
            catch (Exception e)
            {
                Console.WriteLine("Could not import certificate: " + e.Message);
				exitCode = 1;
            }

			Environment.Exit(exitCode);
        }
    }
}
