#!/bin/bash
# ============================================================
# install.sh - Restauración completa de la Raspberry Pi
# Generado: 2026-04-22
# Usuario: cjac89
# ============================================================
# ANTES DE EJECUTAR:
#   1. Copiar los proyectos al home: iol_bot/, mundial2026/,
#      claude_telegram_bot.py, recordatorio_merienda.sh, duckdns/
#   2. Ejecutar como root o con sudo
#   chmod +x install.sh && sudo bash install.sh
# ============================================================

set -e
USER_HOME="/home/cjac89"
USER="cjac89"

echo "=============================="
echo " Instalación Raspberry Pi"
echo "=============================="

# --------------------------------------------------------------
# 1. SISTEMA BASE
# --------------------------------------------------------------
echo "[1/9] Actualizando sistema..."
apt-get update -y && apt-get upgrade -y

echo "[1/9] Instalando paquetes base..."
apt-get install -y \
    curl wget git vim \
    nginx \
    php8.4 php8.4-fpm php8.4-mysql php8.4-mbstring php8.4-xml php8.4-curl php8.4-zip \
    mariadb-server \
    python3 python3-pip python3-venv \
    nodejs npm \
    samba \
    openvpn easy-rsa \
    cron \
    ffmpeg \
    build-essential \
    phpmyadmin

# --------------------------------------------------------------
# 2. PYTHON VIRTUALENV (botenv)
# --------------------------------------------------------------
echo "[2/9] Creando virtualenv botenv..."
sudo -u $USER python3 -m venv $USER_HOME/botenv

echo "[2/9] Instalando dependencias Python en botenv..."
sudo -u $USER $USER_HOME/botenv/bin/pip install --upgrade pip
sudo -u $USER $USER_HOME/botenv/bin/pip install \
    fastapi==0.135.3 \
    uvicorn==0.44.0 \
    aiofiles==25.1.0 \
    httpx==0.28.1 \
    pydantic==2.12.5

# Dependencias del iol_bot (usa python3 del sistema)
echo "[2/9] Instalando dependencias iol_bot..."
pip3 install requests python-dotenv

# --------------------------------------------------------------
# 3. NGINX
# --------------------------------------------------------------
echo "[3/9] Configurando Nginx..."

# Servidor de archivos (port 8080)
cat > /etc/nginx/sites-available/archivos <<'EOF'
server {
    listen 8080;
    server_name _;

    root /var/www/files;
    index index.html;

    location / {
        autoindex on;
        autoindex_exact_size off;
        autoindex_localtime on;
    }

    location ~ \.php$ {
        include snippets/fastcgi-php.conf;
        fastcgi_pass unix:/run/php/php8.4-fpm.sock;
    }
}

server {
    listen 80;
    server_name ccarchivos.duckdns.org;

    root /var/www/files;
    index index.html upload.php;

    location / {
        autoindex on;
        autoindex_exact_size off;
        autoindex_localtime on;
    }

    location ~ \.php$ {
        include snippets/fastcgi-php.conf;
        fastcgi_pass unix:/run/php/php8.4-fpm.sock;
    }

    location ~ /\.ht {
        deny all;
    }
}
EOF

# Generador (ccgenerador)
cat > /etc/nginx/sites-available/generador <<'EOF'
server {
    listen 80;
    server_name ccgenerador.duckdns.org;

    root /var/www/miapp/generator;
    index index.php;

    location / {
        try_files $uri $uri/ /index.php?$query_string;
    }

    location ~ \.php$ {
        include snippets/fastcgi-php.conf;
        fastcgi_pass unix:/run/php/php8.4-fpm.sock;
    }

    location ~ /\.ht {
        deny all;
    }
}
EOF

# App principal / phpMyAdmin
cat > /etc/nginx/sites-available/miapp <<'EOF'
server {
    listen 80;
    server_name _;

    root /var/www/miapp;
    index index.php index.html;

    location / {
        try_files $uri $uri/ =404;
    }

    location ~ \.php$ {
        include snippets/fastcgi-php.conf;
        fastcgi_pass unix:/run/php/php8.4-fpm.sock;
    }

    location ~ /\.ht {
        deny all;
    }

    include snippets/phpmyadmin.conf;
}
EOF

# Activar sitios
ln -sf /etc/nginx/sites-available/archivos  /etc/nginx/sites-enabled/archivos
ln -sf /etc/nginx/sites-available/generador /etc/nginx/sites-enabled/generador
ln -sf /etc/nginx/sites-available/miapp     /etc/nginx/sites-enabled/miapp
rm -f /etc/nginx/sites-enabled/default

# Directorios web
mkdir -p /var/www/files/windows
mkdir -p /var/www/miapp/generator
chown -R $USER:www-data /var/www/files
chmod -R 775 /var/www/files

nginx -t && systemctl enable nginx && systemctl restart nginx

# --------------------------------------------------------------
# 4. DUCKDNS
# --------------------------------------------------------------
echo "[4/9] Configurando DuckDNS..."
mkdir -p $USER_HOME/duckdns

cat > $USER_HOME/duckdns/duck.sh <<'EOF'
#!/bin/bash
echo url="https://www.duckdns.org/update?domains=mundial2026midh,ccgenerador,ccarchivos&token=ea2d8fa4-b184-4323-9d6c-ed0ddc28e47d&ip=" | curl -k -o /home/cjac89/duckdns/duck.log -K -
EOF

chmod +x $USER_HOME/duckdns/duck.sh
chown $USER:$USER $USER_HOME/duckdns/duck.sh

# Actualizar IP ahora
sudo -u $USER bash $USER_HOME/duckdns/duck.sh

# --------------------------------------------------------------
# 5. IOL BOT (.env)
# --------------------------------------------------------------
echo "[5/9] Configurando iol_bot..."
mkdir -p $USER_HOME/iol_bot

cat > $USER_HOME/iol_bot/.env <<'EOF'
IOL_USERNAME=cjac89@gmail.com
IOL_PASSWORD=Yomismo2012_
EOF

chown $USER:$USER $USER_HOME/iol_bot/.env
chmod 600 $USER_HOME/iol_bot/.env

# Servicio systemd iol_bot
cat > /etc/systemd/system/iol_bot.service <<'EOF'
[Unit]
Description=Bot de Trading IOL - Acciones y Bonos
After=network.target

[Service]
Type=simple
User=cjac89
WorkingDirectory=/home/cjac89/iol_bot
Environment=PYTHONUNBUFFERED=1
ExecStart=/usr/bin/python3 /home/cjac89/iol_bot/main.py
Restart=always
RestartSec=60
StandardOutput=journal
StandardError=journal

[Install]
WantedBy=multi-user.target
EOF

systemctl daemon-reload
systemctl enable iol_bot

# --------------------------------------------------------------
# 6. MUNDIAL 2026
# --------------------------------------------------------------
echo "[6/9] Configurando mundial2026..."
mkdir -p $USER_HOME/mundial2026

# Servicio systemd mundial2026
cat > /etc/systemd/system/mundial2026.service <<'EOF'
[Unit]
Description=Mundial 2026 - App de predicciones
After=network.target

[Service]
Type=simple
User=cjac89
WorkingDirectory=/home/cjac89/mundial2026
ExecStart=/home/cjac89/botenv/bin/uvicorn main:app --host 0.0.0.0 --port 8000
Restart=on-failure
RestartSec=5

[Install]
WantedBy=multi-user.target
EOF

systemctl daemon-reload
systemctl enable mundial2026

# --------------------------------------------------------------
# 7. RECORDATORIO MERIENDA
# --------------------------------------------------------------
echo "[7/9] Configurando recordatorio merienda..."

cat > $USER_HOME/recordatorio_merienda.sh <<'EOF'
#!/bin/bash
BOT_TOKEN='8733421632:AAFh42D9e3K6hnDgx63zI_MT1fbvVSF_76k'
CHAT_ID='8781384998'

case $(date +%u) in
  1) MENSAJE='🥣 Recordatorio de merienda - LUNES

Cereales y barrita' ;;
  2) MENSAJE='🧀 Recordatorio de merienda - MARTES

Salado' ;;
  3) MENSAJE='🍰 Recordatorio de merienda - MIÉRCOLES

Galletitas dulces o torta' ;;
  4) MENSAJE='🍎 Recordatorio de merienda - JUEVES

Frutas cortadas' ;;
  5) MENSAJE='🥛 Recordatorio de merienda - VIERNES

Yogur o cereales' ;;
  *) exit 0 ;;
esac

curl -s -X POST "https://api.telegram.org/bot${BOT_TOKEN}/sendMessage" \
  --data-urlencode "chat_id=${CHAT_ID}" \
  --data-urlencode "text=${MENSAJE}"
EOF

chmod +x $USER_HOME/recordatorio_merienda.sh
chown $USER:$USER $USER_HOME/recordatorio_merienda.sh

# --------------------------------------------------------------
# 8. CRONTAB
# --------------------------------------------------------------
echo "[8/9] Configurando crontab..."

sudo -u $USER crontab - <<'EOF'
@reboot sleep 10 && source /home/cjac89/botenv/bin/activate && python3 /home/cjac89/claude_telegram_bot.py &
*/5 * * * * /home/cjac89/duckdns/duck.sh >/dev/null 2>&1
*/30 * * 6-7 * /home/cjac89/botenv/bin/python3 /home/cjac89/mundial2026/cron_resultados.py >> /home/cjac89/mundial2026/resultados.log 2>&1
0 20 * * 1-5 /home/cjac89/recordatorio_merienda.sh >> /home/cjac89/recordatorio.log 2>&1
# Backup semanal - miércoles 13hs
0 13 * * 3 /home/cjac89/backup_semanal.sh >> /home/cjac89/backup_semanal.log 2>&1
EOF

# --------------------------------------------------------------
# 9. INICIAR SERVICIOS
# --------------------------------------------------------------
echo "[9/9] Iniciando servicios..."
systemctl restart php8.4-fpm
systemctl restart nginx
systemctl start iol_bot
systemctl start mundial2026

echo ""
echo "=============================="
echo " Instalación completa!"
echo "=============================="
echo ""
echo "PENDIENTE - copiar manualmente:"
echo "  - /home/cjac89/iol_bot/         (scripts del bot IOL)"
echo "  - /home/cjac89/mundial2026/      (app FastAPI + DB)"
echo "  - /home/cjac89/claude_telegram_bot.py"
echo "  - /var/www/files/upload.php      (script de subida)"
echo "  - /var/www/files/windows/        (instaladores .exe)"
echo "  - /var/www/miapp/                (app PHP)"
echo ""
echo "Verificar acceso:"
echo "  Archivos:   http://ccarchivos.duckdns.org:8080/windows/"
echo "  Subida:     http://ccarchivos.duckdns.org:8080/upload.php"
echo "  Mundial:    http://mundial2026midh.duckdns.org:8000"
echo "  phpMyAdmin: http://ccarchivos.duckdns.org/phpmyadmin"
echo ""
