#!/bin/bash
# Setup script for auto-deployment on the server
# Run this script on the home server as root or with sudo

set -e

APP_DIR="/home/bini/shorts-maker"
SERVICE_NAME="shorts-maker-webhook"

echo "=== Shorts Maker Auto-Deploy Setup ==="

# 1. Make deploy script executable
echo "1. Setting up deploy script..."
chmod +x "$APP_DIR/deploy.sh"
chmod +x "$APP_DIR/webhook-server.py"

# 2. Create log files with proper permissions
echo "2. Creating log files..."
touch /var/log/shorts-maker-deploy.log
touch /var/log/webhook-server.log
chown bini:bini /var/log/shorts-maker-deploy.log
chown bini:bini /var/log/webhook-server.log

# 3. Generate webhook secret
WEBHOOK_SECRET=$(openssl rand -hex 32)
echo "3. Generated webhook secret: $WEBHOOK_SECRET"
echo "   (Save this for Gitea webhook configuration!)"

# 4. Update systemd service with the secret
echo "4. Installing systemd service..."
sed "s/your-secret-here/$WEBHOOK_SECRET/" "$APP_DIR/shorts-maker-webhook.service" > /etc/systemd/system/$SERVICE_NAME.service

# 5. Reload and start service
echo "5. Starting webhook service..."
systemctl daemon-reload
systemctl enable $SERVICE_NAME
systemctl start $SERVICE_NAME

# 6. Check status
echo ""
echo "=== Setup Complete ==="
echo ""
systemctl status $SERVICE_NAME --no-pager
echo ""
echo "=== Next Steps ==="
echo ""
echo "1. Configure Gitea webhook:"
echo "   - Go to Repository Settings > Webhooks > Add Webhook"
echo "   - Target URL: http://your-server-ip:9000/webhook"
echo "   - HTTP Method: POST"
echo "   - Content Type: application/json"
echo "   - Secret: $WEBHOOK_SECRET"
echo "   - Trigger: Push Events"
echo ""
echo "2. If using firewall, open port 9000:"
echo "   sudo ufw allow 9000/tcp"
echo ""
echo "3. Test by pushing to main branch!"
echo ""
echo "=== Useful Commands ==="
echo "View logs:     journalctl -u $SERVICE_NAME -f"
echo "Restart:       sudo systemctl restart $SERVICE_NAME"
echo "Manual deploy: sudo -u bini $APP_DIR/deploy.sh"
