#!/bin/bash
# Complete Mattermost Deployment Script

set -e

echo "=============================================="
echo "Mattermost Production Deployment"
echo "Domain: mm.crista.love"
echo "=============================================="

# Variables - UPDATE THESE WITH YOUR ACTUAL VALUES
B2_KEY_ID="${B2_KEY_ID:-your-b2-key-id}"
B2_APP_KEY="${B2_APP_KEY:REDACTED_APP_KEY}"
B2_ENDPOINT="${B2_ENDPOINT:-s3.us-west-004.backblazeb2.com}"
B2_BUCKET="${B2_BUCKET:-your-bucket-name}"
SMTP_HOST="${SMTP_HOST:-smtp.gmail.com}"
SMTP_PORT="${SMTP_PORT:-587}"
SMTP_USER="${SMTP_USER:-your-email@gmail.com}"
SMTP_PASS="REDACTED_PASSWORD"

echo "=== Step 1: Install Docker Compose plugin ==="
apt-get update
apt-get install -y docker-compose-plugin unzip

echo "=== Step 2: Install AWS CLI for B2 backups ==="
if ! command -v aws &> /dev/null; then
    curl "https://awscli.amazonaws.com/awscli-exe-linux-x86_64.zip" -o "/tmp/awscliv2.zip"
    unzip -q /tmp/awscliv2.zip -d /tmp
    /tmp/aws/install
    rm -rf /tmp/aws /tmp/awscliv2.zip
fi

# Configure AWS CLI for Backblaze B2
mkdir -p ~/.aws
cat > ~/.aws/credentials << EOF
[default]
aws_access_key_id = ${B2_KEY_ID}
aws_secret_access_key = ${B2_APP_KEY}
EOF

cat > ~/.aws/config << EOF
[default]
region = us-west-004
EOF

echo "=== Step 3: Create directory structure ==="
mkdir -p /opt/mattermost/{config,data,logs,plugins,client/plugins,bleve-indexes,backups}
mkdir -p /etc/nginx/ssl
mkdir -p /var/cache/nginx/mattermost

echo "=== Step 4: Generate PostgreSQL password ==="
POSTGRES_PASSWORD="REDACTED_PASSWORD" rand -base64 32 | tr -dc 'a-zA-Z0-9' | head -c 32)
echo "POSTGRES_PASSWORD="REDACTED_PASSWORD" > /opt/mattermost/.env
chmod 600 /opt/mattermost/.env

echo "=== Step 5: Create Docker Compose file ==="
cat > /opt/mattermost/docker-compose.yml << EOF
services:
  postgres:
    image: postgres:15-alpine
    container_name: mattermost-postgres
    restart: unless-stopped
    security_opt:
      - no-new-privileges:true
    pids_limit: 100
    read_only: true
    tmpfs:
      - /tmp
      - /var/run/postgresql
    volumes:
      - postgres_data:/var/lib/postgresql/data
    environment:
      - POSTGRES_USER=mmuser
      - POSTGRES_PASSWORD="REDACTED_PASSWORD"
      - POSTGRES_DB=mattermost
    networks:
      - mattermost-network
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U mmuser -d mattermost"]
      interval: 10s
      timeout: 5s
      retries: 5

  mattermost:
    image: mattermost/mattermost-team-edition:latest
    container_name: mattermost
    restart: unless-stopped
    depends_on:
      postgres:
        condition: service_healthy
    security_opt:
      - no-new-privileges:true
    pids_limit: 200
    tmpfs:
      - /tmp
    volumes:
      - /opt/mattermost/config:/mattermost/config:rw
      - /opt/mattermost/data:/mattermost/data:rw
      - /opt/mattermost/logs:/mattermost/logs:rw
      - /opt/mattermost/plugins:/mattermost/plugins:rw
      - /opt/mattermost/client/plugins:/mattermost/client/plugins:rw
      - /opt/mattermost/bleve-indexes:/mattermost/bleve-indexes:rw
    environment:
      - TZ=UTC
      - MM_SQLSETTINGS_DRIVERNAME=postgres
      - MM_SQLSETTINGS_DATASOURCE=postgres://mmuser:${POSTGRES_PASSWORD}@postgres:5432/mattermost?sslmode=disable&connect_timeout=10
      - MM_BLEVESETTINGS_INDEXDIR=/mattermost/bleve-indexes
      - MM_SERVICESETTINGS_SITEURL=https://mm.crista.love
      - MM_SERVICESETTINGS_LISTENADDRESS=:8065
      # Email Settings
      - MM_EMAILSETTINGS_ENABLESMTPAUTH=true
      - MM_EMAILSETTINGS_SMTPUSERNAME=${SMTP_USER}
      - MM_EMAILSETTINGS_SMTPPASSWORD="REDACTED_PASSWORD"
      - MM_EMAILSETTINGS_SMTPSERVER=${SMTP_HOST}
      - MM_EMAILSETTINGS_SMTPPORT=${SMTP_PORT}
      - MM_EMAILSETTINGS_CONNECTIONSECURITY=STARTTLS
      - MM_EMAILSETTINGS_FEEDBACKEMAIL=${SMTP_USER}
      - MM_EMAILSETTINGS_REPLYTOADDRESS=${SMTP_USER}
      - MM_EMAILSETTINGS_SENDEMAILNOTIFICATIONS=true
      # File Storage - Backblaze B2
      - MM_FILESETTINGS_DRIVERNAME=amazons3
      - MM_FILESETTINGS_AMAZONS3ACCESSKEYID=${B2_KEY_ID}
      - MM_FILESETTINGS_AMAZONS3SECRETACCESSKEY=${B2_APP_KEY}
      - MM_FILESETTINGS_AMAZONS3BUCKET=${B2_BUCKET}
      - MM_FILESETTINGS_AMAZONS3ENDPOINT=${B2_ENDPOINT}
      - MM_FILESETTINGS_AMAZONS3SSL=true
      - MM_FILESETTINGS_AMAZONS3SIGNV2=false
      - MM_FILESETTINGS_AMAZONS3REGION=us-west-004
      # Security
      - MM_SERVICESETTINGS_ENABLESECURITYFIXALERT=true
      - MM_PASSWORDSETTINGS_MINIMUMLENGTH=10
    ports:
      - "127.0.0.1:8065:8065"
    networks:
      - mattermost-network

networks:
  mattermost-network:
    driver: bridge

volumes:
  postgres_data:
EOF

echo "=== Step 6: Set directory permissions ==="
chown -R 2000:2000 /opt/mattermost/config /opt/mattermost/data /opt/mattermost/logs /opt/mattermost/plugins /opt/mattermost/client/plugins /opt/mattermost/bleve-indexes

echo "=== Step 7: Start Mattermost containers ==="
cd /opt/mattermost
docker compose pull
docker compose up -d

echo "=== Step 8: Wait for Mattermost to be healthy ==="
echo "Waiting for services to start..."
sleep 15

# Wait for Mattermost to be ready
MAX_ATTEMPTS=30
ATTEMPT=0
until curl -sf http://127.0.0.1:8065/api/v4/system/ping > /dev/null 2>&1; do
    ATTEMPT=$((ATTEMPT + 1))
    if [ $ATTEMPT -ge $MAX_ATTEMPTS ]; then
        echo "Mattermost did not become healthy in time. Checking logs..."
        docker compose logs --tail=100
        exit 1
    fi
    echo "Waiting for Mattermost to be ready... (attempt $ATTEMPT/$MAX_ATTEMPTS)"
    sleep 5
done
echo "Mattermost is healthy!"

echo "=== Step 9: Configure Nginx ==="
# Nginx config should already be copied

# Create cache directory
mkdir -p /var/cache/nginx/mattermost
chown www-data:www-data /var/cache/nginx/mattermost

# Enable the site
ln -sf /etc/nginx/sites-available/mattermost /etc/nginx/sites-enabled/mattermost

# Test nginx config
nginx -t

# Reload nginx
systemctl reload nginx

echo "=== Step 10: Set up automated backups ==="
chmod +x /opt/mattermost/backup.sh

# Add cron job for daily backups at 3 AM
(crontab -l 2>/dev/null | grep -v "mattermost/backup.sh"; echo "0 3 * * * /opt/mattermost/backup.sh >> /var/log/mattermost-backup.log 2>&1") | crontab -

echo "=== Step 11: Enable open signups ==="
docker exec mattermost /mattermost/bin/mmctl config set TeamSettings.REDACTED_APP_PASSWORD true --local
docker restart mattermost
sleep 15

echo "=============================================="
echo "Mattermost Deployment Complete!"
echo "=============================================="
echo ""
echo "Access Mattermost at: https://mm.crista.love"
echo ""
echo "Next steps:"
echo "1. Visit https://mm.crista.love to create your admin account"
echo "2. The first user to sign up becomes the system admin"
echo ""
echo "Backup schedule: Daily at 3 AM UTC"
echo "Backups stored in: Backblaze B2 (${B2_BUCKET}/backups/)"
echo ""
echo "Useful commands:"
echo "  View logs:    docker compose -f /opt/mattermost/docker-compose.yml logs -f"
echo "  Restart:      docker compose -f /opt/mattermost/docker-compose.yml restart"
echo "  Manual backup: /opt/mattermost/backup.sh"
echo ""

# Show container status
docker compose ps
