# InMotion VPS Deployment Guide

## Prerequisites
- InMotion VPS account with root/sudo access
- Domain name pointed to VPS IP
- SSH access to server

## Step 1: Server Setup (15 minutes)

### 1.1 Connect to VPS
```bash
ssh root@your-server-ip
# Or if using non-root user:
ssh username@your-server-ip
```

### 1.2 Update System
```bash
sudo apt update && sudo apt upgrade -y
```

### 1.3 Install Node.js 18 LTS
```bash
curl -fsSL https://deb.nodesource.com/setup_18.x | sudo -E bash -
sudo apt install -y nodejs
node --version  # Should show v18.x.x
npm --version
```

### 1.4 Install MongoDB
```bash
# Import MongoDB public key
curl -fsSL https://www.mongodb.org/static/pgp/server-7.0.asc | sudo gpg --dearmor -o /usr/share/keyrings/mongodb-server-7.0.gpg

# Add MongoDB repository
echo "deb [ arch=amd64,arm64 signed-by=/usr/share/keyrings/mongodb-server-7.0.gpg ] https://repo.mongodb.org/apt/ubuntu jammy/mongodb-org/7.0 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-7.0.list

# Install MongoDB
sudo apt update
sudo apt install -y mongodb-org

# Start MongoDB
sudo systemctl start mongod
sudo systemctl enable mongod
sudo systemctl status mongod
```

### 1.5 Install PM2
```bash
sudo npm install -g pm2
```

### 1.6 Install Nginx
```bash
sudo apt install -y nginx
sudo systemctl start nginx
sudo systemctl enable nginx
```

### 1.7 Install Git
```bash
sudo apt install -y git
```

## Step 2: MongoDB Configuration (10 minutes)

### 2.1 Secure MongoDB
```bash
sudo mongosh
```

In MongoDB shell:
```javascript
use admin
db.createUser({
  user: "annaadmin",
  pwd: "GENERATE_STRONG_PASSWORD_HERE",
  roles: [ { role: "userAdminAnyDatabase", db: "admin" }, "readWriteAnyDatabase" ]
})

use anna_stockroom
db.createUser({
  user: "annaapp",
  pwd: "GENERATE_STRONG_PASSWORD_HERE",
  roles: [ { role: "readWrite", db: "anna_stockroom" } ]
})

exit
```

### 2.2 Enable MongoDB Authentication
```bash
sudo nano /etc/mongod.conf
```

Add/modify:
```yaml
security:
  authorization: enabled

net:
  bindIp: 127.0.0.1
```

Restart MongoDB:
```bash
sudo systemctl restart mongod
```

## Step 3: Application Deployment (15 minutes)

### 3.1 Create Application Directory
```bash
sudo mkdir -p /var/www/anna-stockroom
sudo chown -R $USER:$USER /var/www/anna-stockroom
cd /var/www/anna-stockroom
```

### 3.2 Clone Repository
```bash
git clone https://github.com/nsanthosh718/anna-stockroom-enterprise.git .
```

### 3.3 Install Dependencies
```bash
npm install --production
```

### 3.4 Configure Environment
```bash
cp .env.example .env
nano .env
```

Update with production values:
```env
NODE_ENV=production
PORT=3001
DOMAIN=your-domain.com

# Generate with: node -e "console.log(require('crypto').randomBytes(64).toString('hex'))"
JWT_SECRET=YOUR_GENERATED_64_CHAR_SECRET_HERE
JWT_EXPIRE=7d

MONGODB_URI=mongodb://annaapp:YOUR_MONGODB_PASSWORD@localhost:27017/anna_stockroom?authSource=anna_stockroom

RATE_LIMIT_WINDOW=15
RATE_LIMIT_MAX=100

# Optional: Email configuration
EMAIL_HOST=smtp.gmail.com
EMAIL_PORT=587
EMAIL_USER=your_email@gmail.com
EMAIL_PASS=your_app_password
```

### 3.5 Generate JWT Secret
```bash
node -e "console.log(require('crypto').randomBytes(64).toString('hex'))"
# Copy output and paste into .env as JWT_SECRET
```

### 3.6 Test Application
```bash
npm start
# Press Ctrl+C after verifying it starts without errors
```

## Step 4: PM2 Configuration (5 minutes)

### 4.1 Start Application with PM2
```bash
pm2 start ecosystem.config.js --env production
pm2 save
pm2 startup
# Follow the command output instructions
```

### 4.2 Verify PM2 Status
```bash
pm2 status
pm2 logs anna-stockroom --lines 50
```

## Step 5: Nginx Configuration (10 minutes)

### 5.1 Create Nginx Configuration
```bash
sudo nano /etc/nginx/sites-available/anna-stockroom
```

Add configuration:
```nginx
server {
    listen 80;
    server_name your-domain.com www.your-domain.com;

    # Security headers
    add_header X-Frame-Options "SAMEORIGIN" always;
    add_header X-Content-Type-Options "nosniff" always;
    add_header X-XSS-Protection "1; mode=block" always;

    # Logging
    access_log /var/log/nginx/anna-stockroom-access.log;
    error_log /var/log/nginx/anna-stockroom-error.log;

    # Proxy to Node.js application
    location / {
        proxy_pass http://localhost:3001;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_cache_bypass $http_upgrade;
        
        # Timeouts
        proxy_connect_timeout 60s;
        proxy_send_timeout 60s;
        proxy_read_timeout 60s;
    }

    # Static files
    location /uploads {
        alias /var/www/anna-stockroom/uploads;
        expires 30d;
        add_header Cache-Control "public, immutable";
    }

    # Gzip compression
    gzip on;
    gzip_vary on;
    gzip_min_length 1024;
    gzip_types text/plain text/css text/xml text/javascript application/x-javascript application/xml+rss application/json;
}
```

### 5.2 Enable Site
```bash
sudo ln -s /etc/nginx/sites-available/anna-stockroom /etc/nginx/sites-enabled/
sudo nginx -t
sudo systemctl reload nginx
```

## Step 6: SSL Certificate (10 minutes)

### 6.1 Install Certbot
```bash
sudo apt install -y certbot python3-certbot-nginx
```

### 6.2 Obtain SSL Certificate
```bash
sudo certbot --nginx -d your-domain.com -d www.your-domain.com
```

Follow prompts:
- Enter email address
- Agree to terms
- Choose redirect option (2)

### 6.3 Test Auto-Renewal
```bash
sudo certbot renew --dry-run
```

## Step 7: Firewall Configuration (5 minutes)

```bash
sudo ufw allow OpenSSH
sudo ufw allow 'Nginx Full'
sudo ufw enable
sudo ufw status
```

## Step 8: Database Seeding (5 minutes)

### 8.1 Create Default Admin User
```bash
cd /var/www/anna-stockroom
node scripts/seedProducts.js
```

## Step 9: Verification (5 minutes)

### 9.1 Check Services
```bash
sudo systemctl status mongod
sudo systemctl status nginx
pm2 status
```

### 9.2 Test Application
```bash
# Test health endpoint
curl http://localhost:3001/api/health

# Test from browser
https://your-domain.com
```

### 9.3 Check Logs
```bash
pm2 logs anna-stockroom --lines 100
sudo tail -f /var/log/nginx/anna-stockroom-error.log
```

## Step 10: Post-Deployment (10 minutes)

### 10.1 Change Default Admin Password
- Login with default credentials (aa1@hotel.com / password123)
- Go to Profile → Change Password
- Set strong password

### 10.2 Set Up Monitoring
```bash
pm2 install pm2-logrotate
pm2 set pm2-logrotate:max_size 10M
pm2 set pm2-logrotate:retain 7
```

### 10.3 Configure Automated Backups
```bash
sudo nano /root/backup-mongodb.sh
```

Add script:
```bash
#!/bin/bash
BACKUP_DIR="/var/backups/mongodb"
DATE=$(date +%Y%m%d_%H%M%S)
mkdir -p $BACKUP_DIR

mongodump --uri="mongodb://annaapp:YOUR_PASSWORD@localhost:27017/anna_stockroom?authSource=anna_stockroom" --out=$BACKUP_DIR/backup_$DATE

# Keep only last 7 days
find $BACKUP_DIR -type d -mtime +7 -exec rm -rf {} +
```

Make executable and add to cron:
```bash
sudo chmod +x /root/backup-mongodb.sh
sudo crontab -e
```

Add line:
```
0 2 * * * /root/backup-mongodb.sh
```

## Troubleshooting

### Application won't start
```bash
pm2 logs anna-stockroom --lines 100
# Check for errors in logs
```

### MongoDB connection issues
```bash
sudo systemctl status mongod
mongosh -u annaapp -p --authenticationDatabase anna_stockroom
```

### Nginx issues
```bash
sudo nginx -t
sudo tail -f /var/log/nginx/error.log
```

### Port already in use
```bash
sudo lsof -i :3001
# Kill process if needed
sudo kill -9 PID
```

## Maintenance Commands

```bash
# Restart application
pm2 restart anna-stockroom

# View logs
pm2 logs anna-stockroom

# Update application
cd /var/www/anna-stockroom
git pull
npm install --production
pm2 restart anna-stockroom

# Backup database manually
mongodump --uri="mongodb://annaapp:PASSWORD@localhost:27017/anna_stockroom?authSource=anna_stockroom" --out=/var/backups/mongodb/manual_backup

# Check disk space
df -h

# Check memory usage
free -h

# Monitor processes
htop
```

## Security Checklist

- [ ] Strong passwords for MongoDB users
- [ ] JWT_SECRET is 64+ characters random string
- [ ] Firewall configured (UFW)
- [ ] SSL certificate installed
- [ ] MongoDB authentication enabled
- [ ] Default admin password changed
- [ ] Automated backups configured
- [ ] Log rotation configured
- [ ] Server updates scheduled

## Support

If you encounter issues:
1. Check logs: `pm2 logs anna-stockroom`
2. Check Nginx logs: `sudo tail -f /var/log/nginx/anna-stockroom-error.log`
3. Verify services: `sudo systemctl status mongod nginx`
4. Contact: support@annallc.com

## Estimated Total Time: 90 minutes
