#!/bin/dash
#/usr/sbin/sdm-login

# Copyright 2003-2007 Vagrant Cascadian <vagrant@freegeek.org>.
# Licensed under the terms of the GNU General Public License,
# version 2 or any later version.

# getLogin is used to set up login information
getLogin() {
    if [ -x "$(which zenity)" ]; then
        login_info=$(zenity --entry --title="login" --text="$login_text")

        status="$?"
        case $status in
            0) ;;
            1) shutdown=$(xmessage -center -print -buttons shutdown,reboot,sdm \
                "shutdown or reboot or return to sdm?")
                case $shutdown in
                    shutdown) halt
                        exit 10 ;;
                    reboot) reboot 
                        exit 20 ;;
                    sdm) exit 30 ;;
                esac
                ;;
            255) xmessage -center "login failed, misconfigured getLogin function? $status"
                echo "login failed, misconfigured getLogin function? $status"
                exit 1 ;;
        esac
    else
        message="zenity not found, either install zenity or configure sdm for autologin"
        xmessage -timeout -center "$message"
        echo "$message"
    fi
}

hostname=$(hostname)

# set some defaults
sdmsession=/usr/bin/sdm-session

# source generic config file
if [ -r /etc/sdm/sdm.config ]; then
	. /etc/sdm/sdm.config
fi

# source host-specific config file
if [ -r /etc/sdm/sdm.config.$hostname ]; then
	. /etc/sdm/sdm.config.$hostname
fi

if [ -n "$xsetroot" ]; then
    xsetroot $xsetroot
fi

if [ -z "$server" ]; then
	server=server
fi

if [ -z "$sshopts" ]; then
	sshopts="-X -T"
fi

if [ -r "$key" ]; then
    sshopts="$sshopts -i $key"
fi

if [ -z "$login_text" ]; then
    login_text="Welcome to $server"
fi

if [ -e /var/run/sdm.autologin.once ]; then
    autologin="no"
fi

case $autologin in
    yes|y|Y|Yes) ;;
    once) touch /var/run/sdm.autologin.once ;;
    *) getLogin ;;
esac

servername=$(echo $login_info | awk -F @ '{print $2}')
username=$(echo $login_info | awk -F @ '{print $1}')

if [ -z "$login_info" ] && [ -n "$anon_server" ]; then
    servername=$anon_server
fi

if [ -z "$servername" ]; then
    servername=$server
fi

if [ -z "$username" ]; then
    if [ -n "$anon_user" ]; then
        username=$anon_user
    else
        # assume user is the same as hostname
        username=$hostname
    fi
fi

if [ -z "$SSH_ASKPASS" ]; then
    if [ -x "/usr/bin/sdm-ssh-askpass" ]; then
        SSH_ASKPASS="/usr/bin/sdm-ssh-askpass"
    elif [ -x "/usr/bin/ssh-askpass" ]; then
        SSH_ASKPASS="/usr/bin/ssh-askpass"
    fi
fi

if [ ! -x "$SSH_ASKPASS" ]; then
    echo "ERROR: SSH_ASKPASS not found: $SSH_ASKPASS"
    exit 1
fi
export SSH_ASKPASS

ssh $sshopts $username@$servername $sdmsession $command
