#!/usr/bin/env python3
import os
import subprocess
import shutil
import urllib
import time
from pathlib import Path
from urllib.parse import quote

# -----------------------------
# CONFIGURATION
# -----------------------------
SMB_SERVER = "192.168.1.68"
SMB_SHARE = "GDrive"
SMB_USER = "macos"      # <-- optional if guest access
SMB_PASS = "dromischSYNC123987me"      # <-- optional if guest access

#MOUNT_POINT = "/Volumes/GDriveNetwork" # <--- don't use the root volume mount point
MOUNT_POINT = str(Path.home() / "NetworkMounts/GDriveNetwork")
LOCAL_DEST = "/Volumes/ExtraDrive/GDrive"

IGNORE_EXT = {".ppinfocache", ".ptn", ".ptn2", ".ini", ".ini2",".lic",".ds_store",".db"}

TIME_TOLERANCE = 1.0  # seconds

# -----------------------------
# FUNCTIONS
# -----------------------------

def is_mounted():
    return os.path.ismount(MOUNT_POINT)

def mount_share():
    print("Mounting SMB share...")

    # Create mount point if missing
    Path(MOUNT_POINT).mkdir(parents=True, exist_ok=True)

    user = quote(SMB_USER)
    pwd = quote(SMB_PASS)
    
    #smb_url = f"//{SMB_USER}:{SMB_PASS}@{SMB_SERVER}/{SMB_SHARE}"
    smb_url = f"//{user}:{pwd}@{SMB_SERVER}/{SMB_SHARE}"
    

    cmd = ["mount_smbfs", smb_url, MOUNT_POINT]
    result = subprocess.run(cmd, capture_output=True, text=True)

    # subprocess.run(["/usr/bin/osascript", "-e",
    #                 f'mount volume "{smb_url}"'], check=False)
        
    if result.returncode != 0:
       print("Mount failed:", result.stderr.strip())

def sync_files():
    print("Starting sync...")
    start = time.time()

    num_new_files_created = 0
    num_newer_files_copied = 0

    for root, dirs, files in os.walk(MOUNT_POINT):
        rel_path = os.path.relpath(root, MOUNT_POINT)
        dest_dir = os.path.join(LOCAL_DEST, rel_path)

        # Ensure destination folder exists
        Path(dest_dir).mkdir(parents=True, exist_ok=True)

        for file in files:
                        
            # Handle dotfiles like .DS_Store
            if file.startswith("."):
                ext = file.lower()  # treat the whole name as the "extension"
            else:
                ext = os.path.splitext(file)[1].lower()
            
            #ignore certain extensions
            if ext in IGNORE_EXT:
                continue

            src_file = os.path.join(root, file)
            dest_file = os.path.join(dest_dir, file)

            # Copy if missing or newer
            if not os.path.exists(dest_file):
                print(f"Copying new file: {dest_file}")
                shutil.copy2(src_file, dest_file)
                num_new_files_created += 1
            else:
                src_mtime = os.path.getmtime(src_file)
                dest_mtime = os.path.getmtime(dest_file)

                if src_mtime - dest_mtime > TIME_TOLERANCE:
                    print(f"Updating newer file: {dest_file}")
                    shutil.copy2(src_file, dest_file)
                    num_newer_files_copied += 1
                    

    end = time.time()
    duration = end - start
    print("---> Sync complete. <---")
    print(f"--- New Files:{num_new_files_created} Updated Files:{num_newer_files_copied}  ---")
    print(f"--- Sync Completed in {duration:.2f} seconds ---")

# -----------------------------
# MAIN
# -----------------------------
def main():
    if not is_mounted():
        print("Network drive not mounted.")
        mount_share()

    if not is_mounted():
        print("Failed to mount SMB share. Exiting.")
        return

    sync_files()

if __name__ == "__main__":
    main()

