#!/bin/bash

# ==================== backup.sh ====================
cat > /root/backup.sh << 'BACKUP'
#!/bin/bash
BACKUP_DIR="/root/backups"
SOURCE_DIR="/"
KEEP_DAYS=7
LOG="/root/backup.log"

mkdir -p "$BACKUP_DIR"
FILENAME="backup_$(date +%Y%m%d_%H%M%S).tar.gz"

echo "[$(date '+%H:%M:%S')] Backup startet..." | tee -a "$LOG"
echo "[$(date '+%H:%M:%S')] Berechne Größe..." | tee -a "$LOG"

TOTAL=$(du -sb \
    --exclude="$BACKUP_DIR" \
    --exclude="/proc" \
    --exclude="/sys" \
    --exclude="/dev" \
    --exclude="/run" \
    --exclude="/tmp" \
    "$SOURCE_DIR" 2>/dev/null | awk '{print $1}')

echo "[$(date '+%H:%M:%S')] Quelle: $(numfmt --to=iec $TOTAL)" | tee -a "$LOG"

tar -cf - \
    --exclude="$BACKUP_DIR" \
    --exclude="/proc" \
    --exclude="/sys" \
    --exclude="/dev" \
    --exclude="/run" \
    --exclude="/tmp" \
    "$SOURCE_DIR" 2>/dev/null \
| pv -s "$TOTAL" -p -t -e -r 2>&1 \
| gzip > "$BACKUP_DIR/$FILENAME"

echo "[$(date '+%H:%M:%S')] Fertig: $BACKUP_DIR/$FILENAME" | tee -a "$LOG"
SIZE=$(du -sh "$BACKUP_DIR/$FILENAME" | awk '{print $1}')
echo "[$(date '+%H:%M:%S')] Größe: $SIZE" | tee -a "$LOG"

find "$BACKUP_DIR" -name "backup_*.tar.gz" -mtime +$KEEP_DAYS -delete
echo "[$(date '+%H:%M:%S')] Alte Backups bereinigt." | tee -a "$LOG"
BACKUP

# ==================== start-backup.sh ====================
cat > /root/start-backup.sh << 'START'
#!/bin/bash
echo "[$(date '+%H:%M:%S')] Starte Backup..." | tee -a /root/backup.log

bash /root/backup.sh
echo "[$(date '+%H:%M:%S')] Backup abgeschlossen - starte SSL Manager..." | tee -a /root/backup.log

bash /root/ssl-manager.sh
echo "[$(date '+%H:%M:%S')] SSL Manager abgeschlossen." | tee -a /root/backup.log
START

# ==================== ssl-manager.sh ====================
cat > /root/ssl-manager.sh << 'SSL'
#!/bin/bash
DOMAINS_DIR="/opt/tinycp/domains"
LOG="/root/ssl-manager.log"
RENEW_DAYS=30
EMAIL="admin@saoas.website"

log() { echo "[$(date '+%Y-%m-%d %H:%M:%S')] $1" | tee -a "$LOG"; }

if ! command -v certbot &>/dev/null; then
    log "Installiere certbot..."
    apt install certbot -y >> "$LOG" 2>&1
fi

DOMAINS=$(ls "$DOMAINS_DIR" 2>/dev/null)
[ -z "$DOMAINS" ] && log "Keine Domains gefunden" && exit 1

log "=== SSL Manager gestartet ==="

for DOMAIN in $DOMAINS; do
    CERT="$DOMAINS_DIR/$DOMAIN/ssl/ssl-letsencrypt.crt"

    if [ ! -f "$CERT" ]; then
        log "[$DOMAIN] Kein Zertifikat - erstelle neu..."
        ISSUE=true
    else
        EXPIRY=$(openssl x509 -enddate -noout -in "$CERT" 2>/dev/null | cut -d= -f2)
        EXPIRY_EPOCH=$(date -d "$EXPIRY" +%s 2>/dev/null)
        NOW_EPOCH=$(date +%s)
        DAYS_LEFT=$(( (EXPIRY_EPOCH - NOW_EPOCH) / 86400 ))

        if [ "$DAYS_LEFT" -lt "$RENEW_DAYS" ]; then
            log "[$DOMAIN] Läuft in $DAYS_LEFT Tagen ab - erneuere..."
            ISSUE=true
        else
            log "[$DOMAIN] OK - noch $DAYS_LEFT Tage gültig"
            ISSUE=false
        fi
    fi

    if [ "$ISSUE" = true ]; then
        systemctl stop nginx 2>/dev/null

        certbot certonly --standalone \
            -d "$DOMAIN" \
            --email "$EMAIL" \
            --agree-tos \
            --non-interactive \
            >> "$LOG" 2>&1

        if [ $? -eq 0 ]; then
            SRC="/etc/letsencrypt/live/$DOMAIN"
            DST="$DOMAINS_DIR/$DOMAIN/ssl"
            cp "$SRC/fullchain.pem" "$DST/ssl-letsencrypt.crt"
            cp "$SRC/privkey.pem"   "$DST/ssl-letsencrypt.key"
            cp "$SRC/chain.pem"     "$DST/ssl-letsencrypt.ca"
            log "[$DOMAIN] Erfolgreich erneuert"
        else
            log "[$DOMAIN] FEHLER!"
        fi

        systemctl start nginx 2>/dev/null
    fi
done

log "=== SSL Manager abgeschlossen ==="
SSL

# ==================== Berechtigungen ====================
chmod +x /root/backup.sh
chmod +x /root/start-backup.sh
chmod +x /root/ssl-manager.sh

# ==================== Crontab ====================
(crontab -l 2>/dev/null | grep -v start-backup | grep -v ssl-manager
echo "0 3 * * * /root/start-backup.sh") | crontab -

# ==================== pv installieren ====================
apt install pv -y > /dev/null 2>&1

echo ""
echo "==============================="
echo " Installation abgeschlossen!"
echo "==============================="
echo " Startet täglich um 03:00:"
echo "  1. Backup"
echo "  2. SSL Manager (nach Backup)"
echo ""
echo " Logs:"
echo "  /root/backup.log"
echo "  /root/ssl-manager.log"
echo ""
echo " Manuell starten:"
echo "  bash /root/start-backup.sh"
echo "==============================="
