#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Share_This_PC.py  -  run ON the PC whose drives you want to reach (e.g. FILM).

EVERYTHING INSIDE THIS PROGRAM IS ENGLISH (Lars's rule).

What it does (once, as Administrator):
  1. network profile -> Private, File & Printer Sharing + Network Discovery firewall
     groups on, the sharing services set to start automatically,
  2. creates ONE dedicated local account (default 'pcshare') with a random password,
     hidden from the Windows sign-in screen - nobody has to know any real account,
  3. shares every fixed drive as  Drive_<letter>  for that account (the system drive
     read-only, the others full access),
  4. writes  PC_connect.json  next to this file: computer name, IP addresses, account,
     password and share list.  Copy that file (USB) next to PC_Drives.bat on any other PC
     and it connects to all drives with NO typing.  The file holds a password - keep it
     private, never e-mail or publish it.

Run it again whenever you like: it keeps the same account and password (so already
connected PCs keep working) and just repairs whatever is missing.
  --new-password   make a fresh password       --account NAME   use another account name
"""

# *************** DEL 01 - IMPORTS & CONSTANTS ***************
# ToDo: stdlib only.  Windows PowerShell does the real work (full path, never bare name).

import os
import sys
import json
import time
import base64
import ctypes
import socket
import secrets
import string
import subprocess
from pathlib import Path

HERE         = Path(sys.executable).parent if getattr(sys, "frozen", False) else Path(__file__).resolve().parent
CONNECT_FILE = HERE / "PC_connect.json"
DEFAULT_ACCOUNT = "pcshare"
POWERSHELL   = str(Path(os.environ.get("SystemRoot", r"C:\Windows")) /
                   "System32" / "WindowsPowerShell" / "v1.0" / "powershell.exe")
FLAG_ELEVATED = "--elevated"        # guard: we ask for Administrator ONCE, never in a loop


# *************** DEL 02 - HELPERS ***************
def is_admin() -> bool:
    try:
        return ctypes.windll.shell32.IsUserAnAdmin() != 0
    except Exception:
        return False


def elevate_once() -> bool:
    """Re-start this program with Administrator rights ONE time (UAC prompt).
    Returns True when the elevated copy was launched.  The flag stops any loop."""
    if getattr(sys, "frozen", False):
        exe, params = sys.executable, ""
    else:
        exe = sys.executable
        params = f'"{Path(__file__).resolve()}"'
    extra = " ".join(a for a in sys.argv[1:] if a != FLAG_ELEVATED)
    params = f"{params} {extra} {FLAG_ELEVATED}".strip()
    rc = ctypes.windll.shell32.ShellExecuteW(None, "runas", exe, params, str(HERE), 1)
    return rc > 32


def ps(script: str, timeout: int = 180) -> tuple:
    """Run PowerShell code (UTF-8 in and out, errors stop the script).
    Returns (returncode, output text)."""
    full = ("$ErrorActionPreference='Stop'; $ProgressPreference='SilentlyContinue'; "
            "[Console]::OutputEncoding=[Text.Encoding]::UTF8; " + script)
    enc = base64.b64encode(full.encode("utf-16-le")).decode("ascii")
    try:
        r = subprocess.run(
            [POWERSHELL, "-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass",
             "-EncodedCommand", enc],
            capture_output=True, timeout=timeout, stdin=subprocess.DEVNULL,
            creationflags=subprocess.CREATE_NO_WINDOW)
        out = r.stdout.decode("utf-8", "replace").strip()
        if r.returncode != 0:
            err = r.stderr.decode("utf-8", "replace")
            if "#< CLIXML" in err:                 # PowerShell's XML error wrapper: keep text only
                import re as _re
                err = " ".join(_re.findall(r"<S S=\"Error\">(.*?)</S>", err)).replace("_x000D__x000A_", " ")
            out = (out + "\n" + err).strip()
        return r.returncode, out
    except Exception as exc:
        return 1, str(exc)


def step(title: str, script: str, timeout: int = 180) -> bool:
    """Run one setup step and print OK / the reason it failed."""
    rc, out = ps(script, timeout)
    if rc == 0:
        print(f"  [ OK ]  {title}")
        return True
    first = out.splitlines()[0] if out else "failed"
    print(f"  [FAIL]  {title}\n          {first}")
    return False


def new_password(n: int = 16) -> str:
    """Letters + digits only (no characters that need quoting), always mixed."""
    alphabet = string.ascii_letters + string.digits
    while True:
        pw = "".join(secrets.choice(alphabet) for _ in range(n))
        if (any(c.islower() for c in pw) and any(c.isupper() for c in pw)
                and any(c.isdigit() for c in pw)):
            return pw


def load_old() -> dict:
    try:
        return json.loads(CONNECT_FILE.read_text(encoding="utf-8"))
    except Exception:
        return {}


# *************** DEL 03 - THE SETUP STEPS ***************
def step_network() -> bool:
    return step("Network profile set to Private (Windows blocks sharing on 'Public')",
                "Get-NetConnectionProfile | Where-Object {$_.NetworkCategory -ne 'Private'} | "
                "Set-NetConnectionProfile -NetworkCategory Private")


def step_firewall() -> bool:
    # Language-independent group ids: File and Printer Sharing, Network Discovery.
    return step("Firewall: File and Printer Sharing + Network Discovery on",
                "Enable-NetFirewallRule -Group '@FirewallAPI.dll,-28502'; "
                "Enable-NetFirewallRule -Group '@FirewallAPI.dll,-32752'")


def step_services() -> bool:
    script = (
        "foreach ($n in 'LanmanServer','LanmanWorkstation','fdPHost','FDResPub','SSDPSRV') { "
        "  try { Set-Service -Name $n -StartupType Automatic; "
        "        if ((Get-Service $n).Status -ne 'Running') { Start-Service $n } } catch { } }; "
        "if ((Get-Service LanmanServer).Status -ne 'Running') { throw 'The Server service would not start' }")
    return step("Sharing services start automatically", script)


def step_account(account: str, password: str) -> bool:
    script = (
        f"$pw = ConvertTo-SecureString '{password}' -AsPlainText -Force; "
        f"$u = Get-LocalUser -Name '{account}' -ErrorAction SilentlyContinue; "
        f"if ($u) {{ Set-LocalUser -Name '{account}' -Password $pw -PasswordNeverExpires $true; "
        f"          Enable-LocalUser -Name '{account}' }} "
        f"else {{ New-LocalUser -Name '{account}' -Password $pw -PasswordNeverExpires "
        f"          -UserMayNotChangePassword -AccountNeverExpires "
        f"          -Description 'Network access to shared drives' | Out-Null }}; "
        f"Add-LocalGroupMember -SID 'S-1-5-32-545' -Member '{account}' -ErrorAction SilentlyContinue; "
        # hide it from the sign-in screen
        "$k='HKLM:\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Winlogon\\SpecialAccounts\\UserList'; "
        "if (-not (Test-Path $k)) { New-Item $k -Force | Out-Null }; "
        f"New-ItemProperty -Path $k -Name '{account}' -Value 0 -PropertyType DWord -Force | Out-Null")
    return step(f"Account '{account}' ready (hidden from the sign-in screen)", script)


def step_rights(account: str, full: bool) -> bool:
    """Full control = the account is an Administrator here and every drive (the system
    drive too) is shared with full access, so ANY file can be changed or deleted from
    the other PC.  --limited = plain user, system drive read-only."""
    if full:
        return step("Full control: the account may change/delete ANY file on the shared drives",
                    f"Add-LocalGroupMember -SID 'S-1-5-32-544' -Member '{account}' -ErrorAction SilentlyContinue; "
                    "New-ItemProperty -Path 'HKLM:\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Policies\\System' "
                    "-Name 'LocalAccountTokenFilterPolicy' -Value 1 -PropertyType DWord -Force | Out-Null")
    return step("Limited rights: the account is NOT an Administrator",
                f"Remove-LocalGroupMember -SID 'S-1-5-32-544' -Member '{account}' -ErrorAction SilentlyContinue")


def list_drives() -> list:
    """Fixed local drives: [{'letter','label','size_gb','system'}]."""
    rc, out = ps("Get-CimInstance Win32_LogicalDisk -Filter 'DriveType=3' | "
                 "Select-Object DeviceID,VolumeName,Size | ConvertTo-Json -Compress")
    drives = []
    if rc != 0 or not out:
        return drives
    try:
        data = json.loads(out)
    except Exception:
        return drives
    if isinstance(data, dict):
        data = [data]
    sysdrive = os.environ.get("SystemDrive", "C:").upper()
    for d in data:
        dev = (d.get("DeviceID") or "").upper()
        label = (d.get("VolumeName") or "")
        low = label.lower()
        if "google" in low or " - goo" in low or "@" in low:   # Google Drive virtual drives: never share these
            continue
        if len(dev) == 2 and dev[1] == ":":
            drives.append({"letter": dev[0], "label": d.get("VolumeName") or "",
                           "size_gb": round((d.get("Size") or 0) / 1e9),
                           "system": dev == sysdrive})
    return drives


def step_shares(account: str, drives: list, full: bool = True) -> list:
    """Share every drive as Drive_<letter>; returns the list that worked."""
    done = []
    for d in drives:
        name = f"Drive_{d['letter']}"
        read_only = d["system"] and not full
        access = "-ReadAccess" if read_only else "-FullAccess"
        script = (f"if (Get-SmbShare -Name '{name}' -ErrorAction SilentlyContinue) "
                  f"{{ Remove-SmbShare -Name '{name}' -Force }}; "
                  f"New-SmbShare -Name '{name}' -Path '{d['letter']}:\\' {access} '{account}' "
                  f"-Description 'Shared by Share_This_PC' | Out-Null")
        mode = "read only" if read_only else "full access"
        if step(f"Share {name}  ({d['letter']}: {d['label'] or 'no label'}, "
                f"{d['size_gb']} GB, {mode})", script):
            done.append({"share": name, "drive": d["letter"] + ":", "label": d["label"],
                         "size_gb": d["size_gb"], "mode": mode})
    return done


def my_addresses() -> list:
    rc, out = ps("Get-NetIPAddress -AddressFamily IPv4 | Where-Object "
                 "{$_.IPAddress -notmatch '^(127|169\\.254)\\.'} | "
                 "ForEach-Object { $_.IPAddress }")
    return [l.strip() for l in out.splitlines() if l.strip().count(".") == 3] if rc == 0 else []


def check_listening() -> bool:
    try:
        with socket.create_connection(("127.0.0.1", 445), timeout=3):
            return True
    except Exception:
        return False


# *************** DEL 04 - MAIN ***************
def main():
    args = sys.argv[1:]
    account = DEFAULT_ACCOUNT
    if "--account" in args:
        try:
            account = args[args.index("--account") + 1].strip() or DEFAULT_ACCOUNT
        except Exception:
            pass

    print("=" * 66)
    print("  Share this PC - one account, every drive shared, no more login hassle")
    print("=" * 66)

    if not is_admin():
        if FLAG_ELEVATED in args:
            print("\nAdministrator rights were not granted - nothing was changed.")
            input("Press Enter to close ")
            return
        print("\nAdministrator rights are needed - a Windows question will appear ...")
        if not elevate_once():
            print("Could not ask for Administrator rights. Right-click the program "
                  "(or a command prompt) and choose 'Run as administrator'.")
            input("Press Enter to close ")
        return                                   # the elevated copy takes over

    old = load_old()
    keep_pw = (old.get("user") == account and old.get("password_b64")
               and "--new-password" not in args)
    password = (base64.b64decode(old["password_b64"]).decode("utf-8") if keep_pw
                else new_password())

    drives = list_drives()
    if not drives:
        print("No fixed drives found - stopping.")
        input("Press Enter to close ")
        return
    print(f"\nThis PC is  {socket.gethostname().upper()}  and will share:")
    for d in drives:
        print(f"   {d['letter']}:  {d['label'] or '(no label)':<20} {d['size_gb']:>6} GB"
              f"   {'system drive' if d['system'] else ''}")
    print(f"\nAccount used from the other PCs:  {account}   (password is made for you)")
    if input("\nGo ahead? [Y/n] ").strip().lower() in ("n", "no"):
        print("Nothing changed.")
        return

    print("")
    step_network()
    step_firewall()
    step_services()
    if not step_account(account, password):
        print("\nThe account could not be made - stopping, no shares were changed.")
        input("Press Enter to close ")
        return
    full = "--limited" not in args
    step_rights(account, full)
    shares = step_shares(account, drives, full)

    info = {
        "computer":     socket.gethostname().upper(),
        "ips":          my_addresses(),
        "user":         account,
        "password_b64": base64.b64encode(password.encode("utf-8")).decode("ascii"),
        "shares":       shares,
        "made":         time.strftime("%Y-%m-%d %H:%M"),
        "note":         "PRIVATE: holds the password for the network account. Copy only "
                        "by USB next to PC_Drives.bat on your own PCs.",
    }
    try:
        CONNECT_FILE.write_text(json.dumps(info, indent=2), encoding="utf-8")
        print(f"\n  [ OK ]  Connection file written:  {CONNECT_FILE}")
    except Exception as exc:
        print(f"\n  [FAIL]  Could not write {CONNECT_FILE}: {exc}")

    print("\n" + "-" * 66)
    print(f"  Port 445 (file sharing) listening here: {'yes' if check_listening() else 'NO - check a third-party firewall'}")
    print(f"  Names this PC answers to: {info['computer']}   {'  '.join(info['ips'])}")
    print("  Tip: give this PC a fixed IP (router 'address reservation') so the")
    print("  address never changes.")
    print("\n  NEXT: copy  PC_connect.json  by USB to the other PC, put it next to")
    print("  PC_Drives.bat, double-click PC_Drives.bat - it connects without any typing.")
    print("-" * 66)
    input("Press Enter to close ")


if __name__ == "__main__":
    main()
