#!/usr/bin/env node
const fs = require('fs');
const webpush = require('web-push');

function readStdin() {
  return new Promise(resolve => {
    let data = '';
    process.stdin.setEncoding('utf8');
    process.stdin.on('data', chunk => data += chunk);
    process.stdin.on('end', () => resolve(data));
  });
}

(async () => {
  const configPath = process.argv[2] || `${process.env.HOME}/.config/mvlog/push.json`;
  const payload = process.argv[3] || '{}';
  const cfg = JSON.parse(fs.readFileSync(configPath, 'utf8'));
  const input = JSON.parse(await readStdin() || '[]');
  const subs = Array.isArray(input) ? input : [];
  if (!cfg.public_key || !cfg.private_key || !subs.length) return;
  webpush.setVapidDetails(cfg.subject || 'mailto:admin@bubulescu.org', cfg.public_key, cfg.private_key);
  let sent = 0;
  for (const sub of subs) {
    try {
      await webpush.sendNotification(sub, payload);
      sent++;
    } catch (err) {
      const code = err && err.statusCode ? ` status=${err.statusCode}` : '';
      console.error(`push failed${code}: ${err.message || err}`);
    }
  }
  console.log(`push sent: ${sent}/${subs.length}`);
})().catch(err => { console.error(err.stack || err); process.exit(1); });
