#!/data/data/com.termux/files/usr/bin/bash
#
# Termux SMS API Server - Security Setup Script
# Generates and configures the required SMS_API_SECRET environment variable
#

# Color codes for pretty output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
CYAN='\033[0;36m'
BOLD='\033[1m'
NC='\033[0m' # No Color

# Banner
clear
echo -e "${CYAN}╔════════════════════════════════════════════════════════════════════════╗${NC}"
echo -e "${CYAN}║${NC}        ${BOLD}🔐 Termux SMS API Server - Security Setup${NC}                    ${CYAN}║${NC}"
echo -e "${CYAN}╚════════════════════════════════════════════════════════════════════════╝${NC}"
echo ""

# Check if Python is available
if ! command -v python &> /dev/null; then
    echo -e "${RED}❌ ERROR: Python is not installed${NC}"
    echo -e "${YELLOW}Please install Python: pkg install python${NC}"
    exit 1
fi

echo -e "${BLUE}📝 Step 1: Generating secure API key...${NC}"
echo ""

# Generate the API key
API_KEY=$(python -c "import secrets; print(secrets.token_hex(32))")

if [ -z "$API_KEY" ]; then
    echo -e "${RED}❌ Failed to generate API key${NC}"
    exit 1
fi

echo -e "${GREEN}✅ Secure API key generated successfully!${NC}"
echo ""

# Determine shell config file
SHELL_RC=""
if [ -f "$HOME/.bashrc" ]; then
    SHELL_RC="$HOME/.bashrc"
elif [ -f "$HOME/.zshrc" ]; then
    SHELL_RC="$HOME/.zshrc"
else
    SHELL_RC="$HOME/.bashrc"
    touch "$SHELL_RC"
fi

echo -e "${BLUE}📝 Step 2: Saving to ${SHELL_RC}...${NC}"
echo ""

# Check if SMS_API_SECRET already exists in config
if grep -q "SMS_API_SECRET" "$SHELL_RC" 2>/dev/null; then
    echo -e "${YELLOW}⚠️  SMS_API_SECRET already exists in ${SHELL_RC}${NC}"
    echo -e "${YELLOW}Do you want to replace it? (y/n)${NC}"
    read -r response
    if [[ "$response" =~ ^[Yy]$ ]]; then
        # Remove old entry
        sed -i '/export SMS_API_SECRET=/d' "$SHELL_RC"
        echo "export SMS_API_SECRET=\"$API_KEY\"" >> "$SHELL_RC"
        echo -e "${GREEN}✅ Updated existing API key${NC}"
    else
        echo -e "${YELLOW}⏭️  Skipping - keeping existing key${NC}"
        # Use existing key for display
        API_KEY=$(grep "SMS_API_SECRET" "$SHELL_RC" | cut -d'"' -f2)
    fi
else
    # Add new entry
    echo "" >> "$SHELL_RC"
    echo "# Termux SMS API Server Authentication" >> "$SHELL_RC"
    echo "export SMS_API_SECRET=\"$API_KEY\"" >> "$SHELL_RC"
    echo -e "${GREEN}✅ API key saved to ${SHELL_RC}${NC}"
fi

echo ""
echo -e "${BLUE}📝 Step 3: Activating in current session...${NC}"
echo ""

# Export for current session
export SMS_API_SECRET="$API_KEY"

echo -e "${GREEN}✅ API key activated${NC}"
echo ""

# Display summary box
echo -e "${CYAN}╔════════════════════════════════════════════════════════════════════════╗${NC}"
echo -e "${CYAN}║${NC}  ${BOLD}🎉 Setup Complete!${NC}                                                  ${CYAN}║${NC}"
echo -e "${CYAN}╠════════════════════════════════════════════════════════════════════════╣${NC}"
echo -e "${CYAN}║${NC}                                                                        ${CYAN}║${NC}"
echo -e "${CYAN}║${NC}  ${BOLD}Your API Key:${NC}                                                      ${CYAN}║${NC}"
echo -e "${CYAN}║${NC}  ${GREEN}${API_KEY}${NC}  ${CYAN}║${NC}"
echo -e "${CYAN}║${NC}                                                                        ${CYAN}║${NC}"
echo -e "${CYAN}║${NC}  ${BOLD}Saved to:${NC} ${YELLOW}${SHELL_RC}${NC}"
# Pad the line to align with box
printf "${CYAN}║${NC}\n"
echo -e "${CYAN}║${NC}                                                                        ${CYAN}║${NC}"
echo -e "${CYAN}║${NC}  ${BOLD}Status:${NC}                                                            ${CYAN}║${NC}"
echo -e "${CYAN}║${NC}  ${GREEN}✅ Active in current session${NC}                                      ${CYAN}║${NC}"
echo -e "${CYAN}║${NC}  ${GREEN}✅ Will persist across restarts${NC}                                   ${CYAN}║${NC}"
echo -e "${CYAN}║${NC}                                                                        ${CYAN}║${NC}"
echo -e "${CYAN}╚════════════════════════════════════════════════════════════════════════╝${NC}"
echo ""

# Next steps
echo -e "${BOLD}📋 Next Steps:${NC}"
echo ""
echo -e "  ${YELLOW}1.${NC} ${BOLD}Copy this key to your Ubuntu homelab .env file:${NC}"
echo -e "     ${CYAN}TERMUX_API_KEY=${API_KEY}${NC}"
echo -e "     ${CYAN}SMS_API_SECRET=${API_KEY}${NC}"
echo ""
echo -e "  ${YELLOW}2.${NC} ${BOLD}Start the SMS API server:${NC}"
echo -e "     ${CYAN}python ~/projects/sms-campaign-manager/android/termux-sms-api-server.py${NC}"
echo ""
echo -e "  ${YELLOW}3.${NC} ${BOLD}Or use the service manager:${NC}"
echo -e "     ${CYAN}~/bin/sms-service.sh start${NC}"
echo ""

# Verification section
echo -e "${BOLD}🔍 Verification:${NC}"
echo ""
echo -e "  Check if key is set: ${CYAN}echo \$SMS_API_SECRET${NC}"
echo -e "  Expected output:     ${GREEN}${API_KEY}${NC}"
echo ""

# Test the environment variable
CURRENT_VALUE="${SMS_API_SECRET}"
if [ "$CURRENT_VALUE" == "$API_KEY" ]; then
    echo -e "${GREEN}✅ Verification passed - API key is correctly set!${NC}"
else
    echo -e "${YELLOW}⚠️  Note: New terminal sessions will have the key automatically loaded${NC}"
fi

echo ""
echo -e "${CYAN}═══════════════════════════════════════════════════════════════════════${NC}"
echo -e "${GREEN}${BOLD}  Setup complete! Your SMS API server is now secure. 🔒${NC}"
echo -e "${CYAN}═══════════════════════════════════════════════════════════════════════${NC}"
echo ""

# Optional: Save key to a file for easy copying (secured with permissions)
KEY_FILE="$HOME/.sms-api-key"
echo "$API_KEY" > "$KEY_FILE"
chmod 600 "$KEY_FILE"

echo -e "${BLUE}💾 API key also saved to: ${KEY_FILE} (readable only by you)${NC}"
echo ""
