#!/usr/bin/env bash
set -Eeuo pipefail
BASE=/opt/scripts/serverkontroll-updates
SERVICE=/etc/systemd/system/apt-daily-upgrade.service.d/90-serverkontroll-notify.conf
BOOT=/etc/systemd/system/serverkontroll-updates-boot.service
mkdir -p "$BASE" /etc/systemd/system/apt-daily-upgrade.service.d
chmod 700 "$BASE"
cat > "$BASE/notify.py" <<'PY'
#!/usr/bin/env python3
"""Notify on unattended-upgrades activity and a subsequent reboot."""
import argparse
import datetime as dt
import email.message
import json
import os
from pathlib import Path
import re
import smtplib
import subprocess
import sys

BASE = Path('/opt/scripts/serverkontroll-updates')
STATE = BASE / 'state.json'
PENDING = BASE / 'pending-reboot.json'
LOG = Path('/var/log/unattended-upgrades/unattended-upgrades.log')
HOST = '192.168.0.7'
PORT = 25
SENDER = 'serverkontroll@denern.se'
RECIPIENTS = ['dennis@ern.se', 'carsten@mrnobody.nu']

def now():
    return dt.datetime.now(dt.timezone.utc)

def load(path):
    try:
        return json.loads(path.read_text())
    except (OSError, ValueError):
        return {}

def save(path, data):
    tmp = path.with_suffix('.tmp')
    tmp.write_text(json.dumps(data, indent=2) + '\n')
    os.chmod(tmp, 0o600)
    tmp.replace(path)

def send(subject, body):
    msg = email.message.EmailMessage()
    msg['From'] = SENDER
    msg['To'] = ', '.join(RECIPIENTS)
    msg['Subject'] = subject
    msg.set_content(body)
    with smtplib.SMTP(HOST, PORT, timeout=15) as smtp:
        smtp.send_message(msg)

def journal_run():
    """Read the most recent service invocation, not old log files."""
    cmd = ['journalctl', '-u', 'apt-daily-upgrade.service', '-n', '100', '--no-pager', '-o', 'short-iso']
    p = subprocess.run(cmd, capture_output=True, text=True, timeout=15)
    return p.stdout[-12000:] if p.returncode == 0 else ''

def post():
    # Invoked by ExecStartPost, including when the main command exits unsuccessfully.
    state = load(STATE)
    current = now()
    last = dt.datetime.fromisoformat(state['last_checked']) if state.get('last_checked') else current - dt.timedelta(days=2)
    # Only examine log content written since the last check. Log rotation is handled
    # by checking both the active log and the immediately previous rotated file.
    lines = []
    for path in (Path(str(LOG) + '.1'), LOG):
        if not path.exists():
            continue
        try:
            for line in path.read_text(errors='replace').splitlines():
                m = re.match(r'^(\d{4}-\d\d-\d\d) (\d\d:\d\d:\d\d)', line)
                if not m:
                    continue
                stamp = dt.datetime.strptime(' '.join(m.groups()), '%Y-%m-%d %H:%M:%S')
                # unattended-upgrades log timestamps are local time
                stamp = stamp.replace(tzinfo=dt.datetime.now().astimezone().tzinfo).astimezone(dt.timezone.utc)
                if last < stamp <= current + dt.timedelta(minutes=2):
                    lines.append(line)
        except OSError:
            pass
    text = '\n'.join(lines)
    upgraded = [line for line in lines if 'Packages that will be upgraded:' in line]
    failures = [line for line in lines if re.search(r'ERROR|Traceback|Exception|failed', line, re.I)]
    completed = any('All upgrades installed' in line for line in lines)
    # Only report when log provides evidence of installed packages or a failure.
    if upgraded or failures:
        result = 'FEL' if failures else ('KLAR' if completed else 'KONTROLLERA')
        body = ('Server: flatreboot (VMID 111)\n'
                f'Tid: {current.astimezone().strftime("%Y-%m-%d %H:%M:%S %Z")}\n'
                f'Resultat: {result}\n\n'
                'Utdrag ur unattended-upgrades-loggen:\n' + text[-12000:] + '\n\n'
                'Fullständig logg: /var/log/unattended-upgrades/\n')
        try:
            send(f'[flatreboot] Automatiska uppdateringar: {result}', body)
        except Exception as exc:
            print(f'E-post misslyckades: {exc}', file=sys.stderr)
    # Save a reboot marker only if upgrades were observed in this invocation and
    # Debian indicates a reboot is needed. It is not proof of the reboot cause.
    if upgraded and Path('/run/reboot-required').exists():
        save(PENDING, {'created': current.isoformat(), 'boot_id': Path('/proc/sys/kernel/random/boot_id').read_text().strip()})
    save(STATE, {'last_checked': current.isoformat()})

def boot():
    pending = load(PENDING)
    if not pending.get('boot_id'):
        return
    boot_id = Path('/proc/sys/kernel/random/boot_id').read_text().strip()
    if boot_id == pending['boot_id']:
        return
    # Avoid sending a misleading notification long after the upgrade.
    try:
        created = dt.datetime.fromisoformat(pending['created'])
        if now() - created > dt.timedelta(days=3):
            PENDING.unlink(missing_ok=True)
            return
    except (ValueError, KeyError):
        PENDING.unlink(missing_ok=True)
        return
    service = subprocess.run(['systemctl', 'is-active', '--quiet', 'serverkontroll.service']).returncode
    service_state = 'aktiv' if service == 0 else 'inte verifierad som aktiv (kontrollera tjänstens namn/status)'
    body = (f'Servern flatreboot (VMID 111) har startat igen.\n'
            f'Tid: {now().astimezone().strftime("%Y-%m-%d %H:%M:%S %Z")}\n'
            f'Serverkontroll-tjänst: {service_state}\n\n'
            'Före omstarten hade unattended-upgrades installerat uppdateringar '
            'och markerat att omstart behövdes.\n'
            'Observera: detta bevisar inte att omstarten var automatisk; '
            'en manuell omstart under samma period kan också ge detta mejl.\n')
    try:
        send('[flatreboot] Servern startad efter uppdateringsbehov', body)
        PENDING.unlink(missing_ok=True)
    except Exception as exc:
        print(f'E-post misslyckades: {exc}', file=sys.stderr)
        raise

def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('action', choices=['post', 'boot', 'test'])
    args = parser.parse_args()
    if args.action == 'post':
        post()
    elif args.action == 'boot':
        boot()
    else:
        send('[flatreboot] Test av uppdateringsavisering', 'Test från notifieringen på flatreboot.\n')
        print('SMTP-relayn accepterade testmejlet.')

if __name__ == '__main__':
    main()
PY
chmod 700 "$BASE/notify.py"
cat > "$SERVICE" <<'EOF'
[Service]
ExecStartPost=-/usr/bin/python3 /opt/scripts/serverkontroll-updates/notify.py post
EOF
cat > "$BOOT" <<'EOF'
[Unit]
Description=Mail notification after reboot following unattended upgrades
Wants=network-online.target
After=network-online.target serverkontroll.service
ConditionPathExists=/opt/scripts/serverkontroll-updates/pending-reboot.json

[Service]
Type=oneshot
ExecStart=/usr/bin/python3 /opt/scripts/serverkontroll-updates/notify.py boot

[Install]
WantedBy=multi-user.target
EOF
cat > "$BASE/uninstall.sh" <<'EOF'
#!/usr/bin/env bash
set -Eeuo pipefail
read -r -p 'Avinstallera notifieringen för Serverkontroll? [ja/NEJ] ' answer
[[ "$answer" == ja ]] || { echo 'Avbrutet.'; exit 0; }
systemctl disable --now serverkontroll-updates-boot.service 2>/dev/null || true
rm -f /etc/systemd/system/serverkontroll-updates-boot.service
rm -f /etc/systemd/system/apt-daily-upgrade.service.d/90-serverkontroll-notify.conf
systemctl daemon-reload
read -r -p 'Ta även bort notifieringens logg/tillstånd och skript? [ja/NEJ] ' remove
if [[ "$remove" == ja ]]; then rm -rf /opt/scripts/serverkontroll-updates; fi
echo 'Notifieringen avinstallerad. unattended-upgrades och dess timers är oförändrade.'
EOF
chmod 700 "$BASE/uninstall.sh"
systemctl daemon-reload
systemctl enable serverkontroll-updates-boot.service
printf '\nInstallerat. Testa med: python3 %s/notify.py test\n' "$BASE"
printf 'OBS: Bekräftelse efter omstart kan även skickas vid manuell omstart efter uppdatering.\n'
