#!/bin/bash
# Copyright (C) 2026 Stefy Lanza <stefy@nexlab.net>
# SPDX-License-Identifier: GPL-3.0-or-later
# Copyleft: this program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# Upload built Windows installer to website (lisa.nexlab.net)
#
# Prerequisites:
#   - SSH key-based auth to lisa@lisa.nexlab.net
#   - Write access to /var/www/html/files/

set -e
cd "$(cd "$(dirname "$0")" && pwd)/.."

INSTALLER_SRC="./deploy/windows/hermes-node-agent-installer.exe"
REMOTE_USER="lisa"
REMOTE_HOST="lisa.nexlab.net"
REMOTE_PATH="/var/www/html/files/"

# Verify installer exists and was built recently
if [ ! -f "$INSTALLER_SRC" ]; then
    echo "❌ Installer not found: $INSTALLER_SRC"
    echo "   Build it first: ./windows/build-all.sh"
    exit 1
fi

if [ "$(find "$INSTALLER_SRC" -mmin +120)" ]; then
    echo "⚠️  Installer is older than 2 hours"
    echo "   Rebuild? Run: ./windows/build-all.sh"
    read -p "Continue anyway? (y/N): " -n 1 -r
    echo
    if [[ ! $REPLY =~ ^[Yy]$ ]]; then
        exit 1
    fi
fi

echo "=== Upload Hermes Node Agent Installer ==="
echo ""
echo "Source: $INSTALLER_SRC"
echo "Size: $(ls -lh "$INSTALLER_SRC" | awk '{print $5}')"
echo ""
echo "Target: scp://$REMOTE_USER@$REMOTE_HOST$REMOTE_PATH"
echo ""
read -p "Upload? (y/N): " -n 1 -r
echo
if [[ ! $REPLY =~ ^[Yy]$ ]]; then
    exit 0
fi

# Create remote directory
ssh "$REMOTE_USER@$REMOTE_HOST" "mkdir -p $REMOTE_PATH" || {
    echo "❌ Could not connect or create remote directory"
    exit 1
}

# Upload
echo "Uploading..."
scp "$INSTALLER_SRC" "$REMOTE_USER@$REMOTE_HOST:$REMOTE_PATH" || {
    echo "❌ Upload failed"
    exit 1
}

# Verify
ssh "$REMOTE_USER@$REMOTE_HOST" "ls -lh $REMOTE_PATH/hermes-node-agent-installer.exe"

# Set permissions
ssh "$REMOTE_USER@$REMOTE_HOST" "chmod 644 $REMOTE_PATH/hermes-node-agent-installer.exe"

echo ""
echo "✅ Upload complete!"
echo ""
echo "🔗 URL: https://lisa.nexlab.net/files/hermes-node-agent-installer.exe"
echo ""
echo "You can also verify at:"
echo "   https://lisa.nexlab.net/files/"
