#!/bin/sh
# Alpine 5G Router – deploy/update device from this repo
# Run from repo root: ./scripts/deploy.sh [user@host]
# Or: TARGET=root@192.168.1.1 ./scripts/deploy.sh
#
# Copies etc/, scripts/, web/, configure_fm350_5g.sh to the device,
# runs install.sh there, then restarts 5g-router and 5g-webgui.

set -e

ROOT="$(cd "$(dirname "$0")/.." && pwd)"
TARGET="${1:-${TARGET:-root@10.130.60.121}}"
REMOTE_DIR="/tmp/Alpine_5G"
SSH_OPTS="${SSH_OPTS:--o ConnectTimeout=10}"

echo "Deploying Alpine 5G Router to $TARGET"
echo "  Repo root: $ROOT"
echo "  Remote dir: $REMOTE_DIR"
echo ""

# Copy files to device
echo "[1/3] Copying files to $TARGET:$REMOTE_DIR ..."
ssh $SSH_OPTS "$TARGET" "mkdir -p $REMOTE_DIR"
scp $SSH_OPTS -r "$ROOT/etc" "$ROOT/scripts" "$ROOT/configure_fm350_5g.sh" "$TARGET:$REMOTE_DIR/"
if [ -d "$ROOT/web" ] && [ -f "$ROOT/web/app.py" ]; then
  scp $SSH_OPTS -r "$ROOT/web" "$TARGET:$REMOTE_DIR/"
fi
echo "  Done."
echo ""

# Run install on device
echo "[2/3] Running install.sh on device ..."
ssh $SSH_OPTS "$TARGET" "cd $REMOTE_DIR && chmod +x scripts/*.sh 2>/dev/null; chmod +x etc/init.d/* 2>/dev/null; ./scripts/install.sh"
echo ""

# Restart services to pick up changes
echo "[3/3] Restarting services ..."
ssh $SSH_OPTS "$TARGET" "
  service 5g-router restart 2>/dev/null || true
  service 5g-webgui restart 2>/dev/null || true
  echo '  Done.'
"

echo ""
echo "Deployment complete. Device: $TARGET"
echo "  Web GUI: http://<device-ip>:5000"
echo "  SSH:     ssh $TARGET"
