# -*- coding: utf-8; mode: tcl; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- vim:fenc=utf-8:ft=tcl:et:sw=4:ts=4:sts=4

package require tcltest 2
namespace import tcltest::*

set pwd [file dirname [file normalize $argv0]]

source ../port_test_autoconf.tcl
package require macports 1.0

array set ui_options {}
#set ui_options(ports_debug)   yes
#set ui_options(ports_verbose) yes
mportinit ui_options

package require portdeactivate 1.0
package require registry 1.0
source ./library.tcl
macports_worker_init


test activate_start {
    Deactivate start unit test.
    Requires root for setting euid.
} -constraints {
    root
} -setup {
    # file writable $prefix is used to determine whether privilege escalation
    # is needed, so set prefix to a directory unwritable for this user
    set prefix /usr/bin

    # elevateToRoot uses $euid and $egid as the IDs to set
    set euid 0
    set egid 0

} -body {
    # drop privileges; the code won't attempt to elevate privileges without
    # that
    seteuid 333
    if {[catch {portdeactivate::deactivate_start args}] != 0} {
        return "FAIL: couldn't elevate privileges"
    }

    # when uid == 0 and euid == 0, the code will not attempt to elevate
    # privileges
    seteuid 0
    if {[catch {portdeactivate::deactivate_start args}] != 0} {
        return "FAIL: couldn't elevate privileges"
    }
    return "Deactivate_start successful."
} -result "Deactivate_start successful."


test deactivate_main {
    Deactivate main unit test.
} -constraints {
    root
} -setup {
    set destpath $pwd/work/destroot
    set portbuildpath $pwd
    set portdbpath $pwd/dbpath
    set portpath $pwd

    set mport [mportopen file://.]

    # set $version var
    set workername [ditem_key $mport workername]

    # portinstall setup
    interp alias {} _cd {} cd

    # hide all output. Deactivate this for debugging!
    set oldchannels [array get macports::channels]
    set macports::channels(msg)    {}
    set macports::channels(notice) {}

    if {[$workername eval eval_targets install] != 0} {
        return "FAIL: port install failed"
    }

} -body {
    if {[$workername eval eval_targets activate] != 0} {
        return "FAIL: cannot activate port after install"
    }
    if {[$workername eval eval_targets deactivate] != 0} {
        return "FAIL: cannot deactivate port after activate"
    }
    return "Port deactivate successful."

} -cleanup {
    if {[$workername eval eval_targets uninstall] != 0} {
        return "FAIL: uninstall failed"
    }
    if {[$workername eval eval_targets clean] != 0} {
        return "FAIL: clean failed"
    }
    array set macports::channels $oldchannels

    mportclose $mport
} -result "Port deactivate successful."


cleanupTests
