#!/bin/bash
# TaxBaik Server Setup Script
# Run on Ubuntu 26.04 server as root or with sudo

set -e

echo "===== TaxBaik Server Setup ====="

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

# Configuration
DEPLOY_USER="kjh2064"
DB_NAME="taxbaikdb"
DB_USER="taxbaik"
DB_PASSWORD="${DB_PASSWORD:-$(openssl rand -base64 12)}"  # Use env var or generate
DEPLOY_DIR="/home/$DEPLOY_USER"

echo -e "${BLUE}1. Installing .NET 8 Runtime${NC}"
sudo apt-get update
sudo apt-get install -y dotnet-runtime-8.0 aspnetcore-runtime-8.0

echo -e "${BLUE}2. Installing PostgreSQL 18${NC}"
sudo apt-get install -y postgresql postgresql-contrib

echo -e "${BLUE}3. Creating database and user${NC}"
sudo -u postgres psql << EOF
CREATE USER $DB_USER WITH PASSWORD '$DB_PASSWORD';
CREATE DATABASE $DB_NAME OWNER $DB_USER;
GRANT ALL PRIVILEGES ON DATABASE $DB_NAME TO $DB_USER;
EOF

echo -e "${BLUE}4. Creating deployment directories${NC}"
sudo -u $DEPLOY_USER mkdir -p $DEPLOY_DIR/deployments
sudo -u $DEPLOY_USER mkdir -p $DEPLOY_DIR/taxbaik_active
sudo -u $DEPLOY_USER mkdir -p $DEPLOY_DIR/taxbaik_admin_active

echo -e "${BLUE}5. Installing systemd service files${NC}"
sudo cp deploy/taxbaik.service /etc/systemd/system/
sudo cp deploy/taxbaik-admin.service /etc/systemd/system/

# Update environment variables in service files
sudo sed -i "s/YOUR_SECURE_PASSWORD_HERE/$DB_PASSWORD/g" /etc/systemd/system/taxbaik.service
sudo sed -i "s/YOUR_SECURE_PASSWORD_HERE/$DB_PASSWORD/g" /etc/systemd/system/taxbaik-admin.service

echo -e "${BLUE}6. Configuring Nginx${NC}"
sudo mkdir -p /etc/nginx/conf.d
sudo cp deploy/nginx-taxbaik-locations.conf /etc/nginx/conf.d/taxbaik.conf
sudo nginx -t
sudo systemctl reload nginx

echo -e "${BLUE}7. Enabling services${NC}"
sudo systemctl daemon-reload
sudo systemctl enable taxbaik taxbaik-admin
sudo systemctl enable postgresql

echo -e "${GREEN}===== Setup Complete ====="
echo ""
echo "Database credentials:"
echo "  Host: localhost"
echo "  Database: $DB_NAME"
echo "  User: $DB_USER"
echo "  Password: $DB_PASSWORD"
echo ""
echo "Next steps:"
echo "  1. Copy the first deployment to ~/deployments/taxbaik_TIMESTAMP/"
echo "  2. Create symlinks:"
echo "     ln -s ~/deployments/taxbaik_TIMESTAMP ~/taxbaik_active"
echo "     ln -s ~/deployments/taxbaik_admin_TIMESTAMP ~/taxbaik_admin_active"
echo "  3. Start services:"
echo "     sudo systemctl start taxbaik taxbaik-admin"
echo "  4. Verify:"
echo "     sudo systemctl status taxbaik taxbaik-admin"
echo "     curl http://127.0.0.1:5001/taxbaik"
echo "     curl http://127.0.0.1:5002/taxbaik/admin/login"
