"""Verify \\ad2\webshare\For_Web is writable from SSH session (task #12 approach)."""
import base64, subprocess, yaml, paramiko

def pwd():
    r = subprocess.run(['sops','-d','D:/vault/clients/dataforth/ad2.sops.yaml'],
                       capture_output=True, text=True, timeout=30, check=True)
    return yaml.safe_load(r.stdout)['credentials']['password'].replace('\\','')

def ps(c, cmd, to=60):
    enc = base64.b64encode(cmd.encode('utf-16-le')).decode()
    stdin, stdout, stderr = c.exec_command(f'powershell -NoProfile -EncodedCommand {enc}', timeout=to)
    return stdout.read().decode('utf-8','replace'), stderr.read().decode('utf-8','replace'), stdout.channel.recv_exit_status()

c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
c.connect('192.168.0.6', username='sysadmin', password=pwd(), timeout=30, banner_timeout=45, look_for_keys=False, allow_agent=False)
try:
    print('=== UNC access probe ===')
    out, err, rc = ps(c, r'Test-Path "\\ad2\webshare\For_Web"; Test-Path "\\localhost\webshare\For_Web"')
    print(out)

    print('=== Count existing For_Web files ===')
    out, err, rc = ps(c, r'Get-ChildItem "\\ad2\webshare\For_Web" -File -Filter *.TXT -ErrorAction SilentlyContinue | Measure-Object | Select-Object Count | Format-Table -AutoSize')
    print(out)

    print('=== Write test ===')
    out, err, rc = ps(c, r'$f = "\\ad2\webshare\For_Web\_sshwrite_test.txt"; Set-Content -Path $f -Value "ssh session write test 2026-04-12"; if (Test-Path $f) { Write-Host "[OK] write succeeded"; Remove-Item $f; Write-Host "[OK] cleanup" } else { Write-Host "[FAIL]" }')
    print(out)
    if err.strip() and 'CLIXML' not in err:
        print('STDERR:', err[:400])
finally:
    c.close()
