#!/bin/bash
# Run this once on the server machine to generate SSL certificates.
# Requires mkcert: https://github.com/FiloSottile/mkcert
#
# After running this script, install the CA on each device that needs
# to access the system (phones, tablets, other PCs).
#
# Usage: bash setup-ssl.sh [SERVER_IP]
# Example: bash setup-ssl.sh 192.168.1.50

set -e

SERVER_IP="${1:-$(hostname -I | awk '{print $1}')}"
CERT_DIR="$(dirname "$0")/certs"

echo "Setting up SSL for IP: $SERVER_IP"
echo "Certificates will be saved to: $CERT_DIR"

# Install mkcert if not present
if ! command -v mkcert &> /dev/null; then
    echo "Installing mkcert..."
    if command -v apt-get &> /dev/null; then
        sudo apt-get update -q && sudo apt-get install -y mkcert libnss3-tools
    elif command -v brew &> /dev/null; then
        brew install mkcert nss
    else
        echo "ERROR: Please install mkcert manually: https://github.com/FiloSottile/mkcert"
        exit 1
    fi
fi

# Install the local CA (makes this machine trust its own certs)
mkcert -install

# Generate the certificate for this machine's IP (and localhost for dev)
mkdir -p "$CERT_DIR"
mkcert \
    -cert-file "$CERT_DIR/cert.pem" \
    -key-file  "$CERT_DIR/key.pem" \
    "$SERVER_IP" \
    "localhost" \
    "127.0.0.1"

echo ""
echo "Done! Certificates saved to $CERT_DIR"
echo ""
echo "======================================================"
echo "  NEXT STEP: Install the CA on each device"
echo "======================================================"
echo ""
echo "The CA certificate is at:"
mkcert -CAROOT
echo ""
echo "On Android phones:"
echo "  1. Copy the 'rootCA.pem' file from the path above to the phone"
echo "  2. Settings > Security > Install certificate > CA certificate"
echo "  3. Select the rootCA.pem file"
echo ""
echo "On Windows PCs:"
echo "  1. Copy rootCA.pem and rename to rootCA.crt"
echo "  2. Double-click it > Install Certificate > Local Machine"
echo "  3. Place in: Trusted Root Certification Authorities"
echo ""
echo "The apps will then be accessible at:"
echo "  Waiter PWA:        https://$SERVER_IP"
echo "  Manager Dashboard: https://$SERVER_IP:4443"
echo "======================================================"
