#!/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
BUILD_PACKAGES=false
while [[ $# -gt 0 ]]; do
    case $1 in
        --debian)
            BUILD_DEBIAN=true
            shift
            ;;
        --debian-only)
            BUILD_DEBIAN_ONLY=true
            BUILD_DEBIAN=true
            shift
            ;;
        --packages)
            BUILD_PACKAGES=true
            BUILD_DEBIAN=true
            shift
            ;;
        --server-only)
            BUILD_SERVER_ONLY=true
            BUILD_DEBIAN=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 packages (wsssh-server and wsssh-tools)"
            echo "  --debian-only      Build only wsssh-tools Debian package (skip binaries and server)"
            echo "  --packages         Build all Debian packages (equivalent to --debian-only)"
            echo "  --server-only      Build only the server (wssshd) and wsssh-server Debian package"
            echo "  --no-server        Skip building the server (wssshd) and wsssh-server package"
            echo "  --wssshtools-only  Build only the C tools (wssshtools) and wsssh-tools package"
            echo "  --help, -h         Show this help"
            exit 0
            ;;
        *)
            echo "Unknown option: $1"
            echo "Usage: $0 [--debian] [--debian-only] [--packages] [--server-only] [--no-server] [--wssshtools-only] [--help]"
            echo "Try '$0 --help' for more information."
            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 python3 python3-pip python3-setuptools; 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 python3 python3-pip python3-setuptools"
        exit 1
    fi

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

    # Build wsssh-server package if it exists and (not wssshtools-only OR server-only) and not debian-only
    if ([ "$BUILD_WSSSHTOOLS_ONLY" = false ] || [ "$BUILD_SERVER_ONLY" = true ]) && [ "$BUILD_DEBIAN_ONLY" = false ] && [ -d "wsssh-server" ] && [ -d "wsssh-server/debian" ]; then
        echo "Building wsssh-server Debian package..."
        cd wsssh-server
        dpkg-buildpackage -us -uc
        cd ..
        # Move deb file to dist
        mv ../wsssh-server*.deb dist/ 2>/dev/null || true
        echo "wsssh-server package built successfully."
    fi

    # Build wssshtools package if it exists and (not server-only OR debian-only)
    if ([ "$BUILD_SERVER_ONLY" = false ] || [ "$BUILD_DEBIAN_ONLY" = true ]) && [ -d "wssshtools" ] && [ -d "wssshtools/debian" ]; then
        echo "Building wsssh-tools Debian package..."
        cd wssshtools
        dpkg-buildpackage -us -uc
        cd ..
        # Move deb file to dist
        mv ../wsssh-tools*.deb dist/ 2>/dev/null || true
        echo "wsssh-tools package built successfully."
    fi

    if [ "$BUILD_SERVER_ONLY" = true ] && [ ! -d "wsssh-server" ]; then
        echo "Warning: wsssh-server package not available (missing wsssh-server/ directory)"
    fi

    if [ "$BUILD_WSSSHTOOLS_ONLY" = true ] && [ ! -d "wssshtools" ]; then
        echo "Warning: wsssh-tools package not available (missing wssshtools/ directory)"
    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."
    echo "Package available in dist/ directory:"
    if ls dist/wsssh-tools*.deb >/dev/null 2>&1; then
        echo "- dist/wsssh-tools*.deb (C tools Debian package)"
    fi
elif [ "$BUILD_PACKAGES" = true ]; then
    echo "Debian package build complete."
    echo "Packages available in dist/ directory:"
    if ls dist/wsssh-server*.deb >/dev/null 2>&1; then
        echo "- dist/wsssh-server*.deb (wssshd server Debian package)"
    fi
    if ls dist/wsssh-tools*.deb >/dev/null 2>&1; then
        echo "- dist/wsssh-tools*.deb (C tools 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
elif [ "$BUILD_SERVER_ONLY" = true ]; then
    echo "Server-only build complete."
    if [ "$BUILD_NO_SERVER" = false ]; then
        echo "Server binary available in dist/ directory:"
        echo "- dist/wssshd (server with web interface)"
    fi
    if ls dist/wsssh-server*.deb >/dev/null 2>&1; then
        echo "- dist/wsssh-server*.deb (wssshd server Debian package)"
    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 ]; then
        echo "Debian packages available in dist/ directory:"
        if ls dist/wsssh-server*.deb >/dev/null 2>&1; then
            echo "- dist/wsssh-server*.deb (wssshd server Debian package)"
        fi
        if ls dist/wsssh-tools*.deb >/dev/null 2>&1; then
            echo "- dist/wsssh-tools*.deb (C tools Debian package)"
        fi
    fi
fi