#!/bin/bash

## Include utility functions.
. "$XDG_TEST_DIR/include/testassertions.sh"
. "$XDG_TEST_DIR/include/testcontrol.sh"

## Test function
test_menu_advanced_install() {
## Begin the test.
test_start "$FUNCNAME: verify submenus are handled correctly"

# Dependencies section
test_init

USERPATH="$HOME/.local:$HOME/.config"

set_no_display

# Generate .desktop file
use_file "$XDG_TEST_DIR/xdg-desktop-menu/data/menu_item_test.desktop" DESKTOP
use_file "$XDG_TEST_DIR/xdg-desktop-menu/data/menu_item_dummy.desktop" DESKTOP2
use_file "$XDG_TEST_DIR/xdg-desktop-menu/data/menu_item_dummy2.desktop" DESKTOP3
use_file "$XDG_TEST_DIR/xdg-desktop-menu/data/menu_install.directory" DIRECTORY

edit_file "$DIRECTORY" 'XDG UTILS TEST' MENU_NAME "MENU $XDG_TEST_SHORTID"

edit_file "$DESKTOP" 'xdg-test-menu-item-install.tmp' CREATEFILE
edit_file "$DESKTOP" 'Test Menu Item Install' ITEM_TEXT "TEST $XDG_TEST_SHORTID"
edit_file "$DESKTOP" '/tmp' WORK_DIR "$XDG_TEST_TMPDIR"

assert_file "$DESKTOP"
assert_file "$DIRECTORY"

# Verify the test icon is not installed already.
assert_file_not_in_path "$DESKTOP" "$USERPATH"
assert_file_not_in_path "$DIRECTORY" "$USERPATH"

# Test steps section
test_procedure

assert_exit 0 xdg-desktop-menu install "$DIRECTORY" "$DESKTOP" "$DESKTOP2" "$DESKTOP3"
assert_nostdout
assert_nostderr

if [ `whoami` != 'root' ]; then
assert_file_in_path "$DESKTOP" "$USERPATH"
assert_file_in_path "$DESKTOP2" "$USERPATH"
assert_file_in_path "$DESKTOP3" "$USERPATH"
assert_file_in_path "$DIRECTORY" "$USERPATH"
fi

if [ -z "$XDG_TEST_NO_INTERACTIVE" -a `whoami` != 'root' ]; then
assert_interactive "Is there a menu in <main> called '$MENU_NAME'?" y
assert_interactive "Are there exactly 3 items in '<main>/$MENU_NAME' called 'EXTRA ITEM', 'EXTRA ITEM 2' and '$ITEM_TEXT'?" y
fi

assert_exit 0 xdg-desktop-menu uninstall "$DIRECTORY" "$DESKTOP3"
assert_nostdout
assert_nostderr

if [ `whoami` != 'root' ]; then
assert_file_in_path "$DESKTOP" "$USERPATH"
assert_file_in_path "$DESKTOP2" "$USERPATH"
assert_file_not_in_path "$DESKTOP3" "$USERPATH"
assert_file_in_path "$DIRECTORY" "$USERPATH"
fi

if [ -z "$XDG_TEST_NO_INTERACTIVE" -a `whoami` != 'root' ]; then
assert_interactive "Is there still a menu in <main> called '$MENU_NAME'?" y
assert_interactive "Are there exactly 2 items in '<main>/$MENU_NAME' called 'EXTRA ITEM' and '$ITEM_TEXT'?" y
fi

assert_exit 0 xdg-desktop-menu uninstall "$DIRECTORY" "$DESKTOP" "$DESKTOP2"
assert_nostdout
assert_nostderr

if [ `whoami` != 'root' ]; then
assert_file_not_in_path "$DESKTOP" "$USERPATH"
assert_file_not_in_path "$DESKTOP2" "$USERPATH"
assert_file_not_in_path "$DESKTOP3" "$USERPATH"
assert_file_not_in_path "$DIRECTORY" "$USERPATH"
fi

test_result
} 

run_test test_menu_advanced_install
