#!/bin/bash

# build.sh - Main build script for wsssh project
# Handles building wssshd2 server and wssshtools client components
#
# 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/>.

set -e

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
cd "$SCRIPT_DIR"

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
WHITE='\033[1;37m'
BLACK='\033[0;30m'
MAGENTA='\033[0;35m'
CYAN='\033[0;36m'
NC='\033[0m' # No Color


# Display flags side by side
display_flags() {
    echo -e "\e[41m \e[40m                       \e[0m \e[48;5;117m                      \e[0m"
    echo -e "\e[41m  \e[40m                      \e[0m \e[48;5;117m                      \e[0m"
    echo -e "\e[41m   \e[40m                     \e[0m \e[48;5;218m                      \e[0m"
    echo -e "\e[41m    \e[47m                    \e[0m \e[48;5;218m                      \e[0m"
    echo -e "\e[41m     \e[47m                   \e[0m \e[48;5;231m                      \e[0m"
    echo -e "\e[41m    \e[47m                    \e[0m \e[48;5;231m                      \e[0m"
    echo -e "\e[41m   \e[42m                     \e[0m \e[48;5;218m                      \e[0m"
    echo -e "\e[41m  \e[42m                      \e[0m \e[48;5;218m                      \e[0m"
    echo -e "\e[41m \e[42m                       \e[0m \e[48;5;117m                      \e[0m"
    echo -e "                         \e[48;5;117m                      \e[0m"
}

# Display flags at startup
display_flags

# Logging functions
log_info() {
    echo -e "${BLUE}[INFO]${NC} $1"
}

log_success() {
    echo -e "${GREEN}[SUCCESS]${NC} $1"
}

log_warning() {
    echo -e "${YELLOW}[WARNING]${NC} $1"
}

log_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

# Check if we're in the right directory
if [[ ! -d "wssshd2" || ! -d "wssshtools" ]]; then
    log_error "This script must be run from the wsssh project root directory"
    exit 1
fi

# Parse command line arguments
SERVER_ONLY=false
WSSSHTOOLS_ONLY=false
DEBIAN_BUILD=false
CLEANUP=false

while [[ $# -gt 0 ]]; do
    case $1 in
        --server-only)
            SERVER_ONLY=true
            shift
            ;;
        --wssshtools-only)
            WSSSHTOOLS_ONLY=true
            shift
            ;;
        --debian)
            DEBIAN_BUILD=true
            shift
            ;;
        --clean|--cleanup)
            CLEANUP=true
            shift
            ;;
        *)
            log_error "Unknown option: $1"
            echo "Usage: $0 [--server-only|--wssshtools-only] [--debian] [--clean|--cleanup]"
            exit 1
            ;;
    esac
done

# Validate argument combinations
if [[ "$SERVER_ONLY" == true && "$WSSSHTOOLS_ONLY" == true ]]; then
    log_error "--server-only and --wssshtools-only cannot be used together"
    exit 1
fi

if [[ "$CLEANUP" == true && "$DEBIAN_BUILD" == true ]]; then
    log_error "--clean/--cleanup cannot be combined with --debian"
    exit 1
fi

# Cleanup function
cleanup() {
    local target="$1"

    log_info "Cleaning up $target..."

    case "$target" in
        "server")
            if [[ -d "wssshd2" ]]; then
                cd wssshd2
                if [[ -f "Makefile" ]]; then
                    make clean >/dev/null 2>&1 || true
                fi
                rm -f Makefile configure.sh.stamp
                rm -rf html_pages/
                cd ..
            fi
            # Remove server debian artifacts
            rm -rf wsssh-server*.deb wsssh-server*.dsc wsssh-server*.changes wsssh-server*.buildinfo
            ;;
        "wssshtools")
            if [[ -d "wssshtools" ]]; then
                cd wssshtools
                if [[ -f "Makefile" ]]; then
                    make clean >/dev/null 2>&1 || true
                fi
                rm -f Makefile configure.sh.stamp
                cd ..
            fi
            # Remove wssshtools debian artifacts
            rm -rf wsssh-tools*.deb wsssh-tools*.dsc wsssh-tools*.changes wsssh-tools*.buildinfo
            ;;
        "logos")
            # Remove logos artifacts
            rm -rf logos/
            ;;
        "all")
            cleanup "server"
            cleanup "wssshtools"
            cleanup "logos"
            ;;
    esac
}

# Asset preparation function
prepare_assets() {
    log_info "Preparing assets..."

    # Create logos directory if it doesn't exist
    mkdir -p logos

    # Generate logos from image.jpg if imagemagick is available
    if command -v convert >/dev/null 2>&1 && [[ -f "image.jpg" ]]; then
        log_info "Generating logos from image.jpg..."
        for size in 16 32 48 64 128; do
            convert image.jpg -resize ${size}x${size} logos/logo-${size}.png
        done
        # Generate favicon.ico
        convert logos/logo-16.png logos/logo-32.png logos/favicon.ico
    elif [[ ! -f "logos/logo-128.png" ]]; then
        log_warning "ImageMagick not found or image.jpg missing. Using placeholder logo."
        # Create a simple placeholder if no logo exists
        if command -v convert >/dev/null 2>&1; then
            convert -size 128x128 xc:"#4A90E2" -fill white -pointsize 72 -gravity center -annotate +0+0 "WSSSH" logos/logo-128.png
            # Also create favicon from placeholder
            convert logos/logo-128.png -resize 16x16 logos/logo-16.png
            convert logos/logo-128.png -resize 32x32 logos/logo-32.png
            convert logos/logo-16.png logos/logo-32.png logos/favicon.ico
        fi
    fi


    log_success "Assets prepared"
}

# Build server function
build_server() {
    log_info "Building wssshd2 server..."

    cd wssshd2

    # Run configure
    if [[ ! -f "configure.sh.stamp" ]]; then
        log_info "Running configure.sh..."
        chmod +x configure.sh
        ./configure.sh
        touch configure.sh.stamp
    fi

    # Build
    log_info "Compiling wssshd2..."
    make

    cd ..
    log_success "wssshd2 server built successfully"
}

# Build wssshtools function
build_wssshtools() {
    log_info "Building wssshtools..."

    cd wssshtools

    # Run configure
    if [[ ! -f "configure.sh.stamp" ]]; then
        log_info "Running configure.sh..."
        chmod +x configure.sh
        ./configure.sh
        touch configure.sh.stamp
    fi

    # Build
    log_info "Compiling wssshtools..."
    make

    cd ..
    log_success "wssshtools built successfully"
}

# Debian packaging function
build_debian_package() {
    local package_type="$1"

    if ! command -v dpkg-buildpackage >/dev/null 2>&1; then
        log_error "dpkg-buildpackage not found. Please install debian packaging tools."
        exit 1
    fi

    case "$package_type" in
        "server")
            log_info "Building Debian package for wsssh-server..."
            cd wsssh-server
            dpkg-buildpackage -us -uc
            cd ..
            ;;
        "wssshtools")
            log_info "Building Debian package for wsssh-tools..."
            cd wssshtools
            dpkg-buildpackage -us -uc
            cd ..
            ;;
    esac

    log_success "Debian package built successfully"
}

# Main build logic
if [[ "$CLEANUP" == true ]]; then
    # Cleanup mode
    if [[ "$SERVER_ONLY" == true ]]; then
        cleanup "server"
    elif [[ "$WSSSHTOOLS_ONLY" == true ]]; then
        cleanup "wssshtools"
    else
        cleanup "all"
    fi
    log_success "Cleanup completed"
    exit 0
fi

# Validate build options
if [[ "$SERVER_ONLY" == true && "$WSSSHTOOLS_ONLY" == true ]]; then
    log_error "Cannot specify both --server-only and --wssshtools-only"
    exit 1
fi

# Prepare assets (needed for server build)
if [[ "$SERVER_ONLY" == true || "$DEBIAN_BUILD" == true || ( "$SERVER_ONLY" == false && "$WSSSHTOOLS_ONLY" == false ) ]]; then
    prepare_assets
fi

# Build components
if [[ "$SERVER_ONLY" == true ]]; then
    build_server
elif [[ "$WSSSHTOOLS_ONLY" == true ]]; then
    build_wssshtools
else
    # Build both
    build_server
    build_wssshtools
fi

# Debian packaging
if [[ "$DEBIAN_BUILD" == true ]]; then
    if [[ "$SERVER_ONLY" == true ]]; then
        build_debian_package "server"
    elif [[ "$WSSSHTOOLS_ONLY" == true ]]; then
        build_debian_package "wssshtools"
    else
        build_debian_package "server"
        build_debian_package "wssshtools"
    fi
fi

log_success "Build completed successfully!"
