#!/bin/sh

APP_DIR="$(cd "$(dirname "$0")" && pwd)"
RUNTIME_DIR="/tmp/dropbear"
BIN_DIR="$RUNTIME_DIR/bin"
ETC_DIR="$RUNTIME_DIR/etc"
LOG_DIR="$RUNTIME_DIR/log"
PORT="${DROPBEAR_PORT:-22}"
HOSTKEY="$ETC_DIR/dropbear_ed25519_host_key"
LOG_FILE="$LOG_DIR/dropbear.log"
PID_FILE="$RUNTIME_DIR/dropbear.pid"
ENABLE_LOG="${DROPBEAR_LOG:-0}"

if [ -e "$RUNTIME_DIR" ] && [ ! -d "$RUNTIME_DIR" ]; then
    rm -f "$RUNTIME_DIR"
fi

mkdir -p "$BIN_DIR" "$ETC_DIR"
chmod 700 "$ETC_DIR"

if [ "$ENABLE_LOG" = "1" ]; then
    mkdir -p "$LOG_DIR"
else
    rm -f "$LOG_FILE"
    rmdir "$LOG_DIR" 2>/dev/null || true
fi

log_msg() {
    if [ "$ENABLE_LOG" = "1" ]; then
        echo "$*" >> "$LOG_FILE"
    fi
}

if [ ! -f "$APP_DIR/dropbearmulti" ]; then
    log_msg "dropbear: missing $APP_DIR/dropbearmulti"
    exit 1
fi

if [ "$APP_DIR/dropbearmulti" != "$BIN_DIR/dropbearmulti" ]; then
    cp -f "$APP_DIR/dropbearmulti" "$BIN_DIR/dropbearmulti"
fi
chmod 755 "$BIN_DIR/dropbearmulti"

ln -sf "$BIN_DIR/dropbearmulti" "$BIN_DIR/dropbear"
ln -sf "$BIN_DIR/dropbearmulti" "$BIN_DIR/scp"

export PATH="$BIN_DIR:$PATH"

if [ -f "$PID_FILE" ]; then
    old_pid="$(cat "$PID_FILE" 2>/dev/null)"
    if [ -n "$old_pid" ] && kill -0 "$old_pid" 2>/dev/null; then
        log_msg "dropbear: already running pid=$old_pid"
        exit 0
    fi
    rm -f "$PID_FILE"
fi

if [ "$ENABLE_LOG" = "1" ]; then
    "$BIN_DIR/dropbear" -R -E -e -r "$HOSTKEY" -p "$PORT" -P "$PID_FILE" >> "$LOG_FILE" 2>&1 &
    log_msg "dropbear: started pid=$! port=$PORT runtime=$RUNTIME_DIR"
else
    "$BIN_DIR/dropbear" -R -E -e -r "$HOSTKEY" -p "$PORT" -P "$PID_FILE" >/dev/null 2>&1 &
fi
