load_lib "helpers.exp"

set timeout 30

# Setup: make sure the principals we will use have V4 salt
fix_salt "A.setup" testuser notathena notathena
unexpire "A.setup" testuser
unexpire "A.setup" changepw/kerberos

proc kill_admin_server {} {
	global env kill getpid

	set pid [exec $getpid kadmind]
	if {$pid != ""} {
		exec $kill $pid
	}
}

proc start_admin_server {} {
    global ovsec_adm_server_path ovsec_adm_server_name sleep env

    set max_tries 60

    for {set num_tries 0} {$num_tries <= $max_tries} {incr num_tries} {
	if {$num_tries} {
	    exec $sleep 5
	    verbose "$ovsec_adm_server couldn't bind; retrying ($num_tries so far)"
	}
	if {[catch "system {cd $ovsec_adm_server_path; exec $ovsec_adm_server_name}" msg]} {
	    if {[regexp {Address already in use} $msg]} {
		continue
	    }
	    fail "starting $ovsec_adm_server_name: $msg"
	}
	return
    }
    fail "starting $ovsec_adm_server_name: $msg"
}
	
proc remove_changepw_perms {} {
	global remove_changepw_perms

	exec $remove_changepw_perms
}

proc set_changepw_perms { perms } {
        global env

	remove_changepw_perms

	exec echo "changepw/kerberos@SECURE-TEST.OV.COM	$perms" \
		>> $env(K5ROOT)/ovsec_adm.acl
}

# start off with a dead admin server
kill_admin_server

set_changepw_perms "i"
start_admin_server
server_start A.1 "-n" 1 {
	"KADM Server starting in the OVSEC_KADM mode" {}
}
kpasswd_v4 A.1 testuser 2 notathena foobar {
	"Operation requires ``change-password'' privilege" {}
} {
	"$kpasswd_v4: Insufficient access to perform requested operation while attempting to change password." {}
} {
	"Password NOT changed." {}
}
server_exit A.1 -1
kill_admin_server

set_changepw_perms "c"
start_admin_server
server_start A.2 "-n" 1 {
	"KADM Server starting in the OVSEC_KADM mode" {}
}
kpasswd_v4 A.2 testuser 2 notathena foobar {
	"Operation requires ``get'' privilege" {}
} {
	"$kpasswd_v4: Insufficient access to perform requested operation while attempting to change password." {}
} {
	"Password NOT changed." {}
}
server_exit A.2 -1
kill_admin_server

set_changepw_perms "ci"

start_admin_server
