#!/usr/bin/env bash
#
# redeploy.sh — trigger a remote deploy FROM YOUR LAPTOP (Git Bash).
# It SSHes into the server and runs the server-side ./deploy.sh.
#
# Usage:
#   ./redeploy.sh              # pull latest + rebuild
#   ./redeploy.sh --no-pull    # rebuild current checkout
#   ./redeploy.sh --rollback   # restore newest backup on the server
#
# Password (in priority order):
#   1. $DEPLOY_PASS environment variable
#   2. a gitignored `deploy.secret` file next to this script (one line = the pw)
#   3. hidden prompt
set -euo pipefail

HOST=118.95.33.89
PORT=61
USER=root
APPDIR=/opt/bizgaze-support
# Pinned server host key (SHA256). plink -batch won't prompt to cache an
# unknown key, so we pin it here. Verify against the fingerprint plink shows
# on first connect. Override with $DEPLOY_HOSTKEY if the server is rebuilt.
HOSTKEY="${DEPLOY_HOSTKEY:-SHA256:hxfv/hH5aplnM4wOsl+jLjWaXwEeceZ4Uz932/5IoCE}"

DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"

# Locate plink (PuTTY).
PLINK="$(command -v plink 2>/dev/null || true)"
[ -n "$PLINK" ] || PLINK="/c/Program Files/PuTTY/plink"
[ -x "$PLINK" ] || { echo "ERROR: plink not found (install PuTTY or add to PATH)"; exit 1; }

# Resolve password.
PW="${DEPLOY_PASS:-}"
if [ -z "$PW" ] && [ -f "$DIR/deploy.secret" ]; then
  PW="$(tr -d '\r\n' < "$DIR/deploy.secret")"
fi
if [ -z "$PW" ]; then
  read -rsp "Server password for $USER@$HOST: " PW; echo
fi

echo "==> Triggering deploy on $USER@$HOST ($APPDIR) …"
exec "$PLINK" -ssh -batch -hostkey "$HOSTKEY" -P "$PORT" -pw "$PW" "$USER@$HOST" "cd $APPDIR && bash deploy.sh $*"
