#!/usr/bin/env ruby.ruby3.4

# Copyright 2025 Open Text
#
# ------------------------------------------------------------------------------
# The only warranties for products and services of Open Text and its
# affiliates and licensors (“Open Text”) are as may be set forth in the express
# warranty statements accompanying such products and services.  Nothing herein
# should be construed as constituting an additional warranty. Open Text shall not
# be liable for technical or editorial errors or omissions contained herein. The
# information contained herein is subject to change without notice.
#
# Except as specifically indicated otherwise, this document contains
# confidential information and a valid license is required for possession, use or
# copying. If this work is provided to the U.S. Government, consistent with FAR
# 12.211 and 12.212, Commercial Computer Software, Computer Software
# Documentation, and Technical Data for Commercial Items are licensed to the U.S.
# Government under vendor's standard commercial license.
# ------------------------------------------------------------------------------

# Copyright (C) [2007-2008] Novell, Inc.  All Rights Reserved.

# THIS WORK IS SUBJECT TO U.S. AND INTERNATIONAL COPYRIGHT LAWS AND TREATIES.
# IT MAY NOT BE USED, COPIED, DISTRIBUTED, DISCLOSED, ADAPTED, PERFORMED,
# DISPLAYED, COLLECTED, COMPILED, OR LINKED WITHOUT NOVELL'S PRIOR WRITTEN
# CONSENT.  USE OR EXPLOITATION OF THIS WORK WITHOUT AUTHORIZATION COULD
# SUBJECT THE PERPETRATOR TO CRIMINAL AND CIVIL LIABILITY.

# NOVELL PROVIDES THE WORK "AS IS," WITHOUT ANY EXPRESS OR IMPLIED WARRANTY,
# INCLUDING WITHOUT THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE, AND NON-INFRINGEMENT. NOVELL, THE AUTHORS OF THE WORK,
# AND THE OWNERS OF COPYRIGHT IN THE WORK ARE NOT LIABLE FOR ANY CLAIM, DAMAGES,
# OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT, OR OTHERWISE,
# ARISING FROM, OUT OF, OR IN CONNECTION WITH THE WORK OR THE USE OR OTHER
# DEALINGS IN THE WORK.

# :title: Novell Migration Utility - migcred
# ==Description: casa (House)
#
# ---
# ==Arguments:
#  c, credentials The credential to store the user name and password under.
#  d, delete      Delete the credential from the migration store
#  g, prompt      Prompt for the credentials.
#  G, generate    Try to generate the other credentials from the specified one.
#  p, print       Print the credentials specified by option c to stdout.
#  u, user        The user name to be stored.
#  w, password    The user's password to be stored.
#  W, windows	  Sets the user name to be stored as a windows users name not ldap
# ---
# ==Output:

require 'rubygems'
require 'mig'
require 'pp'
require 'logger'
options = {}
store = {}

def main
  include Migration
	
  $argdef = [
#		['p', 'prompt',
#			"Prompt the user for the credential",
#			ParseArgBool, false],
		['n', 'nds_dn',
	                "distinguished Name (ND_NDAP), ex. admin.company",
			 ParseArgBool, false],
                ['r', 'retrieve',
	                 "retrieve and print the credentials specified by option c to stdout",
			 ParseArgBool, false],
#		['E', 'environment',
#			 "Specify password with MIGPWD environment variable",
#			 ParseArgBool, false],
		['N', 'nds_fdn',
			 "Fully Distinguished Name (FDN_NDAP), ex. cn=admin.o=company", 
			 ParseArgBool,false],
		['c', 'cn',
			 "common Name (CN), ex. John Smith",
			 ParseArgBool, false],
		['o', 'other',
			 "non specified credential",
			 ParseArgBool, false],
		['i', 'id',
			 "the id or key to identify the credential",
			 ParseArgText, true],
		['d', 'delete',
			 "delete the credential",
			 ParseArgBool, false],
		['W', 'windows',
			 "sets the user name to be stored as a windows users name not LDAP",
			 ParseArgBool, false],
#		['g', 'generate',
#			 "Try to generate the other credential types from the specified one",
#			 ParseArgBool, false],
		['w', 'password',
			 "specify LDAP username and password",
			 ParseArgBool, false],
		['e', 'email',
			 "e-mail address, ex. admin@company.com",
			 ParseArgBool, false],
		['l', 'ldap_dn',
			 "Fully Distinguished LDAP Name (DN_LDAP), ex. cn=admin,o=company",
			 ParseArgBool, false],
		[nil, 'debug', "generate debug log", ParseArgBool],
		ParseArgHelp,
                ParseArgUsage
	]
  
  migcredCommand = "#{$0}"
  debugOpt = false
  $*.each do |arg|
    if arg.strip == "--debug"
       debugOpt = true
    end
    migcredCommand += " #{arg}"
  end
  initLog(debugOpt, "migcred")
  print_message(DEBUG, "migcred command started at #{`date +%d-%m-%y\\ %H:%M:%S`}.")
  print_message(DEBUG, "migcred command executed as: #{migcredCommand}")
 

 (options,extraargs) = parseargs(ARGV, $argdef)

  credential = {}
  if not options['i']
    print_message(FATAL, "You must specify the id of the system ")
    printUsage($argdef)
    exit 1
    #MigrationException.new(Lang::E_MISSREQARGS, {:i => 'id'})
  end
  if options['w'] and not options['r']
    print_message(FATAL, "You must specify option 'r' along with option 'w' ")
    printUsage($argdef)
    exit 1
  end
  if options['d'] and options['r']
    print_message(FATAL, "Options 'r' and 'd' cannot be speicified together")
    printUsage($argdef)
    exit 1
  end

  #Find the credential type
  if options['c'] or options['W']
    credential[:cn] = options['c'] || options['W']
  end
  
  credential[:email] =   options['e']   if options['e']
  credential[:ldap_dn] = options['l'] if options['l']
  credential[:nds_dn] =  options['n']  if options['n']
  credential[:nds_fdn] = options['N'] if options['N']
  credential[:other] =   options['o']   if options['o']

  if credential.empty? and not options['d']
    print_message(FATAL, "You must specify one of the following options: 'c','e','l','n','N','o','W' ")
    printUsage($argdef)
    exit 1
    #raise MigrationException.new(Lang::E_MISSREQARGS, {:c => 'c,e,l,n,N,o,W'})
  end
  
  #Delete
  if options['d']
    KeyStore.remove( options['i'] )
  #Print
  elsif options['r']
    credential.each_key do |key|
      store = KeyStore.retrieve( :basic, options['i'], key, true)
      
      if store.nil? or store.empty?
        raise MigrationException.new(Lang::E_MIGCRED_NOCRED, {:key => key})
      end
  	 
	  #options.each_key {|k| puts k}
	  if options['w']
	    puts "password: #{store[:password]} "
	  else
	    puts "#{key}: #{store[:username]}"
	  end

      store.clear      
    end

  else
    if credential.length > 1
      raise MigrationException.new(Lang::E_MIGCRED_NOCRED)
    end
    KeyStore.credential( options['i'], credential.shift.first, true, true)  
  end
  
  exit 0
end

begin
  main
rescue ArgumentError => e
  print_message(FATAL, "ArgumentError, " + e.to_s)
  exit 1
rescue StandardError => e
  print_message(FATAL, "StandardError, " + e.to_s)
  exit 1
rescue MigrationException => e
  print_message(FATAL,"MigrationException, " + e.to_s)
  exit e.code
rescue MigSyntaxError => e
  print_message(FATAL, "MigSyntaxError, " + e.to_s)
  printUsage($argdef)
  exit e.code
rescue Interrupt
  print_message(DEBUG, "Interrupted by user")
  exit 1
rescue => discription
  print_message(FATAL, "Caught exception: #{$!.message}\n Backtrace:\n #{$!.backtrace.join("\n")}")
  exit 1
ensure 
  options.clear
  store.clear
end
