const fs = require('fs');
const crypto = require('crypto');
const path = require('path');

const CERT_PATH = path.join(__dirname, '../root.crt');
const OUTPUT_PATH = path.join(__dirname, '../root.mobileconfig');

function generateUUID() {
  return crypto.randomUUID().toUpperCase();
}

function generateMobileConfig() {
  try {
    console.log('Generating Apple mobile configuration profile...');
    console.log('Reading certificate from:', CERT_PATH);

    // Read certificate
    const certPem = fs.readFileSync(CERT_PATH, 'utf8');

    // Extract base64 content (remove PEM headers and newlines)
    const certBase64 = certPem
      .replace('-----BEGIN CERTIFICATE-----', '')
      .replace('-----END CERTIFICATE-----', '')
      .replace(/\s/g, '');

    // Generate UUIDs for profile and payload
    const profileUUID = generateUUID();
    const payloadUUID = generateUUID();

    const mobileconfig = `<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>PayloadContent</key>
    <array>
        <dict>
            <key>PayloadCertificateFileName</key>
            <string>root.crt</string>
            <key>PayloadContent</key>
            <data>
            ${certBase64}
            </data>
            <key>PayloadDescription</key>
            <string>Root CA certificate for Sami Home Network</string>
            <key>PayloadDisplayName</key>
            <string>Sami Home Network Root CA</string>
            <key>PayloadIdentifier</key>
            <string>com.sami-home.ca.root-ca</string>
            <key>PayloadType</key>
            <string>com.apple.security.root</string>
            <key>PayloadUUID</key>
            <string>${payloadUUID}</string>
            <key>PayloadVersion</key>
            <integer>1</integer>
        </dict>
    </array>
    <key>PayloadDescription</key>
    <string>Install the Sami Home Network Root CA to trust locally-issued certificates for *.sami domains.</string>
    <key>PayloadDisplayName</key>
    <string>Sami Home Network Root CA</string>
    <key>PayloadIdentifier</key>
    <string>com.sami-home.ca</string>
    <key>PayloadOrganization</key>
    <string>Sami Home Network</string>
    <key>PayloadRemovalDisallowed</key>
    <false/>
    <key>PayloadType</key>
    <string>Configuration</string>
    <key>PayloadUUID</key>
    <string>${profileUUID}</string>
    <key>PayloadVersion</key>
    <integer>1</integer>
</dict>
</plist>
`;

    fs.writeFileSync(OUTPUT_PATH, mobileconfig);
    console.log('✓ Mobile configuration profile generated successfully!');
    console.log('  Output:', OUTPUT_PATH);
    console.log('  Profile UUID:', profileUUID);
    console.log('  Payload UUID:', payloadUUID);
    console.log('\nTo install on iOS:');
    console.log('  1. Download root.mobileconfig to your device');
    console.log('  2. Open Settings app (it should prompt automatically)');
    console.log('  3. Tap "Install Profile" and follow the prompts');
    console.log('  4. Go to Settings > General > About > Certificate Trust Settings');
    console.log('  5. Enable full trust for "Sami Home Network Root CA"');
    console.log('\nTo install on macOS:');
    console.log('  1. Download root.mobileconfig');
    console.log('  2. Open System Settings > Privacy & Security > Profiles');
    console.log('  3. Click the profile and click Install');

    return { profileUUID, payloadUUID };
  } catch (error) {
    console.error('Error generating mobile configuration profile:', error.message);
    process.exit(1);
  }
}

// Run if called directly
if (require.main === module) {
  generateMobileConfig();
}

module.exports = { generateMobileConfig };
