#!/bin/sh
set -eu

host="${HOST_SSH_HOST}"
port="${HOST_SSH_PORT}"
user="${HOST_SSH_USER}"
key="${HOST_SSH_KEY}"
fallback_cwd="${HOST_REMOTE_CWD}"
requested_cwd="${UNIDESK_REQUESTED_CWD:-$fallback_cwd}"
login_shell="${HOST_LOGIN_SHELL}"

quote() {
  printf "'%s'" "$(printf '%s' "$1" | sed "s/'/'\\''/g")"
}

q_requested=$(quote "$requested_cwd")
q_fallback=$(quote "$fallback_cwd")
q_shell=$(quote "$login_shell")
remote_cmd="cd $q_requested 2>/dev/null || cd $q_fallback 2>/dev/null || cd; export UNIDESK_BRIDGE=host-ssh; exec $q_shell -l"
tty_arg="-T"
if [ -t 0 ] && [ -t 1 ]; then
  tty_arg="-tt"
fi

exec ssh "$tty_arg" \
  -i "$key" \
  -p "$port" \
  -o BatchMode=yes \
  -o StrictHostKeyChecking=accept-new \
  -o UserKnownHostsFile=/tmp/unidesk-host-known-hosts \
  -o ServerAliveInterval=20 \
  -o ServerAliveCountMax=3 \
  "$user@$host" "$remote_cmd"
