#!/bin/bash

# WebSocket SSH Tools Build Script
# Build script for WebSocket SSH tools (wssshd, wssshc, wsscp, etc.)
#
# Copyright (C) 2024 Stefy Lanza <stefy@nexlab.net> and SexHack.me
#
# 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.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <https://www.gnu.org/licenses/>.

# Parse command line arguments
BUILD_DEBIAN=false
BUILD_DEBIAN_ONLY=false
BUILD_SERVER_ONLY=false
BUILD_NO_SERVER=false
BUILD_WSSSHTOOLS_ONLY=false
while [[ $# -gt 0 ]]; do
    case $1 in
        --debian)
            BUILD_DEBIAN=true
            shift
            ;;
        --debian-only)
            BUILD_DEBIAN_ONLY=true
            BUILD_DEBIAN=true
            shift
            ;;
        --server-only)
            BUILD_SERVER_ONLY=true
            shift
            ;;
        --no-server)
            BUILD_NO_SERVER=true
            shift
            ;;
        --wssshtools-only)
            BUILD_WSSSHTOOLS_ONLY=true
            shift
            ;;
        --help|-h)
            echo "Usage: $0 [options]"
            echo "Options:"
            echo "  --debian           Build Debian package"
            echo "  --debian-only      Build only Debian package (skip binaries)"
            echo "  --server-only      Build only the server (wssshd)"
            echo "  --no-server        Skip building the server (wssshd)"
            echo "  --wssshtools-only  Build only the C tools (wssshtools)"
            echo "  --help, -h         Show this help"
            exit 0
            ;;
        *)
            echo "Unknown option: $1"
            echo "Usage: $0 [--debian] [--debian-only] [--server-only] [--no-server] [--wssshtools-only]"
            exit 1
            ;;
    esac
done


# Create dist directory if not exists
mkdir -p dist

# Skip Python/C building if --debian-only or --wssshtools-only is specified
if [ "$BUILD_DEBIAN_ONLY" = false ] && [ "$BUILD_WSSSHTOOLS_ONLY" = false ]; then
    # Check if virtual environment exists, create if not
    if [ ! -d "venv" ]; then
        echo "Creating virtual environment..."
        python3 -m venv venv
    fi

    # Activate virtual environment
    . venv/bin/activate

    # Install requirements
    echo "Installing requirements..."
    pip3 install -r requirements.txt

    # Install pyinstaller if not already installed
    pip3 install pyinstaller
    # Generate SSL certificates if they don't exist
    if [ ! -f "cert.pem" ] || [ ! -f "key.pem" ]; then
        echo "Generating SSL certificates..."
        openssl req -x509 -newkey rsa:4096 -keyout key.pem -out cert.pem -days 365 -nodes -subj "/C=US/ST=State/L=City/O=Organization/CN=localhost"
    fi

    # Generate logos and icons from image.jpg if it exists
    if [ -f "image.jpg" ] && command -v convert &> /dev/null; then
        echo "Generating logos and icons..."
        mkdir -p logos

        # Generate various logo sizes
        convert image.jpg -resize 512x512 logos/logo-512.png
        convert image.jpg -resize 256x256 logos/logo-256.png
        convert image.jpg -resize 128x128 logos/logo-128.png
        convert image.jpg -resize 64x64 logos/logo-64.png

        # Generate icon sizes
        for size in 16 32 48 64 128 256; do
            convert image.jpg -resize ${size}x${size} logos/icon-${size}.png
        done

        # Generate additional assets
        convert image.jpg -resize 800x200 logos/banner-800x200.png
        convert image.jpg -quality 100 logos/logo-high-quality.png
        convert image.jpg -resize 32x32 logos/favicon.ico

        echo "Logo generation complete."
    fi

    # Build Python binaries
    echo "Building Python binaries..."

    # Build wssshd (server) binary unless --no-server is specified
    if [ "$BUILD_NO_SERVER" = false ]; then
        pyinstaller --onefile --distpath dist --add-data "cert.pem:." --add-data "key.pem:." --add-data "templates:templates" --add-data "logos:logos" --runtime-tmpdir /tmp --clean wssshd.py
    fi

    # Build client binaries
    if [ "$BUILD_SERVER_ONLY" = false ]; then
        # Build wssshc (client) binary
        pyinstaller --onefile --distpath dist --runtime-tmpdir /tmp --clean wssshc.py

        # Build wsssh and wsscp binaries unless --no-server is specified
        if [ "$BUILD_NO_SERVER" = false ]; then
            # Build wsssh binary
            pyinstaller --onefile --distpath dist --runtime-tmpdir /tmp --clean wsssh.py

            # Build wsscp binary
            pyinstaller --onefile --distpath dist --runtime-tmpdir /tmp --clean wsscp.py
        fi
    fi
fi

# Build C version if wssshtools directory exists and not debian-only
if [ "$BUILD_DEBIAN_ONLY" = false ] && [ -d "wssshtools" ]; then
    echo "Building C version..."
    cd wssshtools
    if [ -f "configure.sh" ]; then
        ./configure.sh
        if [ "$BUILD_WSSSHTOOLS_ONLY" = true ]; then
            # Build all C tools for wssshtools-only mode
            make
        elif [ "$BUILD_NO_SERVER" = true ]; then
            # Build only wssshc for no-server mode
            make wssshc
        elif [ "$BUILD_SERVER_ONLY" = true ]; then
            # Skip C tools build for server-only mode
            echo "Skipping C tools build for server-only mode"
        else
            make
        fi
        cd ..
    else
        echo "Warning: configure.sh not found in wssshtools/"
        cd ..
    fi
fi

# Build Debian package if requested
if [ "$BUILD_DEBIAN" = true ]; then
    echo "Checking Debian build dependencies..."

    # Check for required Debian build tools
    missing_deps=""
    for dep in debhelper gcc make pkg-config libssl-dev; do
        if ! dpkg -l | grep -q "^ii  $dep"; then
            missing_deps="$missing_deps $dep"
        fi
    done

    if [ -n "$missing_deps" ]; then
        echo "Error: Missing Debian build dependencies:$missing_deps"
        echo "Please install them with: sudo apt-get install$missing_deps"
        echo "Or run: sudo apt-get install debhelper gcc make pkg-config libssl-dev"
        exit 1
    fi

    echo "All Debian build dependencies found."
    echo "Building Debian package..."

    if [ -d "wssshtools" ] && [ -d "wssshtools/debian" ]; then
        cd wssshtools
        dpkg-buildpackage -us -uc
        cd ..
        # Move deb file to dist
        mv ../wsssh-tools*.deb dist/ 2>/dev/null || true
    else
        echo "Warning: Debian packaging not available (missing wssshtools/debian/)"
    fi
fi

# Deactivate venv if it was activated
if [ "$BUILD_DEBIAN_ONLY" = false ] && [ "$BUILD_WSSSHTOOLS_ONLY" = false ]; then
    deactivate
fi

if [ "$BUILD_DEBIAN_ONLY" = true ]; then
    echo "Debian package build complete."
    if ls dist/wsssh-tools*.deb >/dev/null 2>&1; then
        echo "Package available in dist/ directory:"
        echo "- dist/wsssh-tools*.deb (Debian package)"
    fi
elif [ "$BUILD_WSSSHTOOLS_ONLY" = true ]; then
    echo "C tools build complete."
    if [ -d "wssshtools" ] && [ -f "wssshtools/wssshc" ]; then
        echo "C tools available in wssshtools/ directory:"
        echo "- wssshtools/wssshc (C client)"
        echo "- wssshtools/wsssh (C SSH wrapper)"
        echo "- wssshtools/wsscp (C SCP wrapper)"
    fi
else
    echo "Build complete. Binaries are in dist/ directory:"

    if [ "$BUILD_NO_SERVER" = false ]; then
        echo "- dist/wssshd (server with web interface)"
    fi

    if [ "$BUILD_SERVER_ONLY" = false ]; then
        echo "- dist/wssshc (client)"
        if [ "$BUILD_NO_SERVER" = false ]; then
            echo "- dist/wsssh (SSH wrapper)"
            echo "- dist/wsscp (SCP wrapper)"
        fi
    fi

    if [ -d "wssshtools" ] && [ -f "wssshtools/wssshc" ]; then
        if [ "$BUILD_NO_SERVER" = true ]; then
            echo "- wssshtools/wssshc (C client)"
        elif [ "$BUILD_SERVER_ONLY" = false ]; then
            echo "- wssshtools/wssshc (C client)"
            echo "- wssshtools/wsssh (C SSH wrapper)"
            echo "- wssshtools/wsscp (C SCP wrapper)"
        fi
    fi

    if [ "$BUILD_DEBIAN" = true ] && ls dist/wsssh-tools*.deb >/dev/null 2>&1; then
        echo "- dist/wsssh-tools*.deb (Debian package)"
    fi
fi