package com.foxx.androidcast.remoteaccess;

import android.content.Context;
import android.util.Log;

import org.apache.sshd.common.util.OsUtils;
import org.apache.sshd.common.util.io.PathUtils;
import org.bouncycastle.jce.provider.BouncyCastleProvider;

import java.nio.file.Path;
import java.security.Security;
import java.util.concurrent.atomic.AtomicBoolean;

/** One-time MINA SSHD + BouncyCastle setup for Android (see mina-sshd docs/android.md). */
final class RsshSecuritySetup {
    private static final String TAG = "RsshSecurity";
    private static final AtomicBoolean READY = new AtomicBoolean(false);

    private RsshSecuritySetup() {}

    static void ensureReady(Context context) {
        if (!READY.compareAndSet(false, true)) {
            return;
        }
        Context app = context.getApplicationContext();
        try {
            try {
                Security.removeProvider(BouncyCastleProvider.PROVIDER_NAME);
            } catch (Exception ignored) {
            }
            if (Security.getProvider(BouncyCastleProvider.PROVIDER_NAME) == null) {
                Security.addProvider(new BouncyCastleProvider());
            }
            Path home = app.getFilesDir().toPath();
            System.setProperty("user.home", home.toString());
            PathUtils.setUserHomeFolderResolver(() -> home);
            OsUtils.setCurrentUser(app.getPackageName());
            Log.i(TAG, "SSHD security providers ready; user.home=" + home);
        } catch (Exception e) {
            READY.set(false);
            Log.e(TAG, "SSHD security setup failed: " + e.getMessage(), e);
            throw new IllegalStateException("RSSH security setup failed", e);
        }
    }
}
