#!/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.
# Hermes Node Protocol
# Copyright (c) 2026 Stefy (nextime) Lanza <stefy@nexlab.net>
# All rights reserved.
# 
# This software is released under the MIT License with a copyleft clause.
# See the LICENSE file for full terms.
set -e

echo "=== Building Linux Distribution ==="

# Create dist directory
mkdir -p dist

# Create temporary build directory
BUILD_DIR=$(mktemp -d)
PACKAGE_DIR="$BUILD_DIR/hermes-node-agent"
mkdir -p "$PACKAGE_DIR"

echo "Copying files to $PACKAGE_DIR..."

# Copy core files from repo-root source of truth
cp hermes_node_agent.py "$PACKAGE_DIR/hermes_node_agent.py"
cp browser_controller.py "$PACKAGE_DIR/"
cp requirements.txt "$PACKAGE_DIR/"
cp install.sh "$PACKAGE_DIR/install.sh"
cp hermes-node-agent.init.d "$PACKAGE_DIR/"
cp hermes-node-agent.service "$PACKAGE_DIR/"

# Copy documentation
cp README.md "$PACKAGE_DIR/"
cp LICENSE "$PACKAGE_DIR/"
cp DEPLOYMENT.md "$PACKAGE_DIR/"
cp PROTOCOL.md "$PACKAGE_DIR/"
cp BROWSER_PROTOCOL.md "$PACKAGE_DIR/"

# Create tarball
cd "$BUILD_DIR"
tar czf hermes-node-agent-linux.tar.gz hermes-node-agent/
mv hermes-node-agent-linux.tar.gz "$OLDPWD/dist/"
cd "$OLDPWD"

# Re-embed the packaged payload into the self-contained Linux installer wrapper
python3 <<'PY'
import base64, pathlib, re
src = pathlib.Path('dist/hermes-node-agent-linux.tar.gz').read_bytes()
b64 = base64.b64encode(src).decode('ascii')
installer_path = pathlib.Path('deploy/linux/install-node.sh')
text = installer_path.read_text()
pattern = r"(cat <<'TARBALL_DATA' \| base64 -d \| tar xzf -\n)(.*?)(\nTARBALL_DATA)"
new_text, count = re.subn(pattern, lambda m: m.group(1) + b64 + m.group(3), text, flags=re.S)
if count != 1:
    raise SystemExit(f'Expected exactly one TARBALL_DATA block in {installer_path}, found {count}')
pathlib.Path('deploy/linux/install-node.sh').write_text(new_text)
print('✅ Re-embedded packaged payload into deploy/linux/install-node.sh')
PY

# Cleanup
rm -rf "$BUILD_DIR"

echo "✅ Linux package created: dist/hermes-node-agent-linux.tar.gz"
echo ""
echo "To deploy:"
echo "  scp dist/hermes-node-agent-linux.tar.gz user@node:~/"
echo "  ssh user@node"
echo "  tar xzf hermes-node-agent-linux.tar.gz"
echo "  cd hermes-node-agent"
echo "  sudo ./install.sh"
