#!/bin/bash

# Colors for terminal output
GREEN='\033[0;32m'
BLUE='\033[0;34m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

echo -e "${BLUE}=== Setting up Postaci on Ubuntu Server ===${NC}"

# Update system
echo -e "${YELLOW}Updating system packages...${NC}"
apt update && apt upgrade -y

# Install Node.js, npm, and other dependencies
echo -e "${YELLOW}Installing Node.js and dependencies...${NC}"
curl -fsSL https://deb.nodesource.com/setup_18.x | bash -
apt install -y nodejs postgresql postgresql-contrib nginx git

# Check Node.js and npm versions
echo -e "${GREEN}Installed Node.js version:${NC}"
node -v
echo -e "${GREEN}Installed npm version:${NC}"
npm -v

# Start and enable PostgreSQL
echo -e "${YELLOW}Setting up PostgreSQL...${NC}"
systemctl start postgresql
systemctl enable postgresql

# Create PostgreSQL user and database
echo -e "${YELLOW}Creating PostgreSQL user and database...${NC}"
sudo -u postgres psql -c "CREATE USER postaci WITH PASSWORD 'postaci_password';"
sudo -u postgres psql -c "CREATE DATABASE postaci OWNER postaci;"
sudo -u postgres psql -c "GRANT ALL PRIVILEGES ON DATABASE postaci TO postaci;"

# Clone the repository
echo -e "${YELLOW}Cloning repository...${NC}"
git clone https://gitea.oezdag.io/m3mo/POSTERAPP_V1.git /root/postaci

# Set up the application
echo -e "${YELLOW}Setting up the application...${NC}"
cd /root/postaci

# Install dependencies
echo -e "${YELLOW}Installing npm dependencies...${NC}"
npm install
cd validation-service && npm install && cd ..

# Create production environment file
echo -e "${YELLOW}Creating environment configuration...${NC}"
cat > .env.production << EOL
# Next Auth
NEXTAUTH_SECRET=$(openssl rand -base64 32)
NEXTAUTH_URL=http://$(curl -s ifconfig.me)

# Database
DATABASE_URL="postgresql://postaci:postaci_password@localhost:5432/postaci"

# API Services
API_URL="http://localhost:8000/api"
EOL

# Generate Prisma client and run migrations
echo -e "${YELLOW}Setting up database...${NC}"
npx prisma generate
npx prisma migrate deploy

# Build Next.js app
echo -e "${YELLOW}Building Next.js application...${NC}"
npm run build

# Create service files for validation service
echo -e "${YELLOW}Creating validation service...${NC}"
cat > /etc/systemd/system/validation-service.service << EOL
[Unit]
Description=Address Validation Service for Postaci
After=network.target

[Service]
Type=simple
User=root
WorkingDirectory=/root/postaci/validation-service
ExecStart=/usr/bin/node server.js
Restart=on-failure
Environment=NODE_ENV=production

[Install]
WantedBy=multi-user.target
EOL

# Create service file for Next.js app
echo -e "${YELLOW}Creating Next.js service...${NC}"
cat > /etc/systemd/system/nextjs.service << EOL
[Unit]
Description=Next.js Application for Postaci
After=network.target

[Service]
Type=simple
User=root
WorkingDirectory=/root/postaci
ExecStart=/usr/bin/npm start
Restart=on-failure
Environment=NODE_ENV=production

[Install]
WantedBy=multi-user.target
EOL

# Configure Nginx
echo -e "${YELLOW}Configuring Nginx...${NC}"
cat > /etc/nginx/sites-available/postaci << EOL
server {
    listen 80;
    server_name _;

    location / {
        proxy_pass http://localhost:3000;
        proxy_http_version 1.1;
        proxy_set_header Upgrade \$http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host \$host;
        proxy_cache_bypass \$http_upgrade;
    }
}
EOL

# Enable the Nginx configuration
ln -s /etc/nginx/sites-available/postaci /etc/nginx/sites-enabled/
rm /etc/nginx/sites-enabled/default
systemctl restart nginx

# Start and enable the services
echo -e "${YELLOW}Starting services...${NC}"
systemctl enable validation-service
systemctl start validation-service
systemctl enable nextjs
systemctl start nextjs

# Set up firewall
echo -e "${YELLOW}Configuring firewall...${NC}"
ufw allow 22
ufw allow 80
ufw allow 443
echo "y" | ufw enable

echo -e "${GREEN}=== Deployment complete! ===${NC}"
echo -e "Your application should be available at http://$(curl -s ifconfig.me)"
echo -e "Make sure to set up HTTPS for production use." 