#!/bin/bash

# Deploy Script for Go Lead Application
# Usage: ./deploy.sh

set -e

echo "🚀 Starting deployment of Go Lead Application..."

# Configuration
APP_NAME="go-lead"
APP_DIR="/var/www/html/advice/_go.lead"
SERVICE_NAME="go-lead.service"
BUILD_OUTPUT="leadapp"

# Colors for output
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
RED='\033[0;31m'
NC='\033[0m' # No Color

# Check if Go is installed
if ! command -v go &> /dev/null; then
    echo -e "${RED}❌ Go is not installed. Please install Go first.${NC}"
    exit 1
fi

echo -e "${YELLOW}📦 Building application...${NC}"
go build -o $BUILD_OUTPUT main.go

if [ $? -ne 0 ]; then
    echo -e "${RED}❌ Build failed!${NC}"
    exit 1
fi

echo -e "${GREEN}✅ Build successful!${NC}"

# Set permissions
chmod +x $BUILD_OUTPUT

# Check if systemd service exists
if [ -f "/etc/systemd/system/$SERVICE_NAME" ]; then
    echo -e "${YELLOW}🔄 Restarting service...${NC}"
    sudo systemctl restart $SERVICE_NAME
    
    # Check service status
    if systemctl is-active --quiet $SERVICE_NAME; then
        echo -e "${GREEN}✅ Service restarted successfully!${NC}"
    else
        echo -e "${RED}❌ Service failed to start. Check logs with: sudo journalctl -u $SERVICE_NAME${NC}"
        exit 1
    fi
else
    echo -e "${YELLOW}⚠️  Service file not found. Please install the service first.${NC}"
    echo "Run: sudo cp go-lead.service /etc/systemd/system/"
    echo "Then: sudo systemctl daemon-reload && sudo systemctl enable go-lead && sudo systemctl start go-lead"
fi

# Check if app is running on port 9087
sleep 2
if netstat -tlnp 2>/dev/null | grep -q ":9087"; then
    echo -e "${GREEN}✅ Application is running on port 9087${NC}"
else
    echo -e "${YELLOW}⚠️  Application might not be running on port 9087${NC}"
fi

echo ""
echo -e "${GREEN}🎉 Deployment completed!${NC}"
echo ""
echo "Access the application at:"
echo "  - Local: http://localhost:9087"
echo "  - Public: https://advice.ezmember.org/_go.lead"
echo ""
echo "Useful commands:"
echo "  - Check status: sudo systemctl status go-lead"
echo "  - View logs: sudo journalctl -u go-lead -f"
echo "  - Restart: sudo systemctl restart go-lead"
