#!/bin/sh

alterator_api_version=1
hooks_dir=/usr/lib/alterator/hooks/vnc.d/

. alterator-sh-functions

## installer support, $ALTERATOR_DESTDIR - exported by installer.

DESTDIR=""
CHROOT_EXEC=""

if [ -d "${ALTERATOR_DESTDIR:-}" ]; then
    DESTDIR="$ALTERATOR_DESTDIR"
    CHROOT_EXEC="chroot $DESTDIR"
fi

## VNC's password management

vnc_chpasswd()
{
    if [ -n "${CHROOT_EXEC-}" ]; then
        $CHROOT_EXEC "/bin/mkdir -p /root/.vnc"
        $CHROOT_EXEC "/usr/bin/x11vnc -storepasswd $1 /root/.vnc/passwd"
    else
        /bin/mkdir -p /root/.vnc
        /usr/bin/x11vnc -storepasswd "$1" /root/.vnc/passwd
    fi

    #little run-parts
    for f in "$DESTDIR/$hooks_dir"/*; do
	      [ -f "$f" -a -x "$f" ] || continue
	      [ "${f%.rpm*}" = "$f" -a "${f%\~}" = "$f" ] || continue

	      echo "$1"| $CHROOT_EXEC "${f#$DESTDIR}" >&2
    done
}

change_password()
{
    if test_bool "$in_auto" && [ -z "$in_passwd_auto" ]; then
	      write_error "`_ "You should define a password for VNC server"`"
    elif test_bool "$in_auto" && [ -n "$in_passwd_auto" ]; then
	      vnc_chpasswd "$in_passwd_auto"
    elif [ -z "$in_passwd_1" -a -z "$in_passwd_2" ]; then
	      write_error "`_ "You should define a password for VNC server"`"
    elif [ "$in_passwd_1" != "$in_passwd_2" ]; then
	      write_error "`_ "Passwords mismatch"`"
    else
	      vnc_chpasswd "$in_passwd_1"
    fi
}

generate_password()
{
    write_string_param passwd_auto "$(pwqgen)"
}

alterator_export_proc change_password
alterator_export_proc generate_password

message_loop
