#!/bin/bash

# configure.sh - Configuration script for wssshtools C implementation

echo "Configuring wssshtools..."

# Check for required tools
echo "Checking for required tools..."

if ! command -v gcc &> /dev/null; then
    echo "Error: gcc not found. Please install gcc."
    exit 1
fi

if ! command -v make &> /dev/null; then
    echo "Error: make not found. Please install make."
    exit 1
fi

if ! command -v pkg-config &> /dev/null; then
    echo "Error: pkg-config not found. Please install pkg-config."
    exit 1
fi

# Check for OpenSSL development libraries
if ! pkg-config --exists openssl; then
    echo "Error: OpenSSL development libraries not found."
    echo "Please install openssl-dev or libssl-dev package."
    exit 1
fi

echo "All required tools found."

# Generate Makefile
cat > Makefile << 'EOF'
# Makefile for wssshtools

CC = gcc
CFLAGS = -Wall -Wextra -O2 $(shell pkg-config --cflags openssl)
LDFLAGS = $(shell pkg-config --libs openssl)

# Source files
SRCS = wssshc.c wsssh.c wsscp.c
OBJS = $(SRCS:.c=.o)
TARGETS = wssshc wsssh wsscp

# Man pages
MANPAGES = man/wssshc.1 man/wsssh.1 man/wsscp.1

# Default target
all: $(TARGETS)

# Individual targets
wssshc: wssshc.o
	$(CC) $(CFLAGS) -o $@ $^ $(LDFLAGS)

wsssh: wsssh.o
	$(CC) $(CFLAGS) -o $@ $^ $(LDFLAGS)

wsscp: wsscp.o
	$(CC) $(CFLAGS) -o $@ $^ $(LDFLAGS)

# Object files
%.o: %.c
	$(CC) $(CFLAGS) -c $< -o $@

# Clean
clean:
	rm -f $(OBJS) $(TARGETS)

# Install (optional)
install: all
	install -d $(DESTDIR)/usr/local/bin
	install -m 755 $(TARGETS) $(DESTDIR)/usr/local/bin/
	install -d $(DESTDIR)/usr/local/share/man/man1
	install -m 644 $(MANPAGES) $(DESTDIR)/usr/local/share/man/man1/

# Uninstall (optional)
uninstall:
	rm -f $(DESTDIR)/usr/local/bin/wssshc
	rm -f $(DESTDIR)/usr/local/bin/wsssh
	rm -f $(DESTDIR)/usr/local/bin/wsscp
	rm -f $(DESTDIR)/usr/local/share/man/man1/wssshc.1
	rm -f $(DESTDIR)/usr/local/share/man/man1/wsssh.1
	rm -f $(DESTDIR)/usr/local/share/man/man1/wsscp.1

.PHONY: all clean install uninstall
EOF

echo "Makefile generated successfully."

# Create configure stamp
touch configure.sh.stamp

echo "Configuration complete. Run 'make' to build the C tools."