#!/bin/sh
set -eu

# Wake's Rust synchronizer invokes `ssh` directly and through rsync. This
# wrapper supplies a per-host non-interactive password only when the host was
# added with password authentication; key-based hosts pass straight through.
config_root="${WAKE_CONFIG_ROOT:-/lzcapp/var/config}"
# OpenSSH resolves ~/.ssh via the passwd entry, not the HOME environment.
# Always select this instance's managed config, including rsync's SSH calls.
ssh_config="$config_root/.ssh/config"
if [ ! -r "$ssh_config" ]; then
  echo "Wake SSH config is missing; save the remote host connection first" >&2
  exit 255
fi
unset WAKE_SSH_PASSWORD_FILE SSH_ASKPASS SSH_ASKPASS_REQUIRE
host=""
skip_next=0
for argument in "$@"; do
  if [ "$skip_next" -eq 1 ]; then
    skip_next=0
    continue
  fi
  case "$argument" in
    --) ;;
    -o|-p|-l|-F|-i|-J|-b|-c|-D|-E|-I|-L|-m|-O|-Q|-R|-S|-W|-w) skip_next=1 ;;
    -*) ;;
    *) host="$argument"; break ;;
  esac
done

if [ -n "$host" ]; then
  credential_id=$(printf %s "$host" | sha256sum | awk '{print $1}')
  password_file="$config_root/.ssh/passwords/$credential_id"
  if [ -r "$password_file" ]; then
    export WAKE_SSH_PASSWORD_FILE="$password_file"
    export SSH_ASKPASS=/lzcapp/pkg/content/lzc/ssh-askpass.sh
    export SSH_ASKPASS_REQUIRE=force
    export DISPLAY=:0
    # OpenSSH uses the first value: override the core's BatchMode=yes only
    # for a host with an instance-managed password.
    exec /usr/bin/ssh -F "$ssh_config" -oBatchMode=no "$@"
  fi
fi

exec /usr/bin/ssh -F "$ssh_config" "$@"
