import boto3
import os
from botocore.config import Config

# Configurações Civo (extraídas do arquivo de credenciais)
ACCESS_KEY = "0UZ69TH03Q292DMTB82B"
SECRET_KEY = "JJ5XXZYvoWdnqBCNP5oREjACyrXeH6EgSqeSybT7"
ENDPOINT = "https://objectstore.nyc1.civo.com"
BUCKET_NAME = "rede5"
REGION = "NYC1"

SSH_DIR = os.path.expanduser("~/.ssh")
S3_PREFIX = "vault/ssh/"

def sync_to_civo():
    print(f"--- Sincronizando ~/.ssh com Civo Object Storage ({BUCKET_NAME}) ---")
    
    # Configurar cliente S3 compatível
    s3 = boto3.client(
        's3',
        aws_access_key_id=ACCESS_KEY,
        aws_secret_access_key=SECRET_KEY,
        endpoint_url=ENDPOINT,
        region_name=REGION,
        config=Config(
            signature_version='s3v4',
            s3={'addressing_style': 'path'}
        )
    )

    files_to_sync = [
        "civo", "github", "ic-ad", "cloudflare-token", 
        "cloudflare-token-inventcloud", "coolify-redbull-token",
        "forgejo-token", "github-token", "monday.env", 
        "bookstack-token", "openproject-token"
    ]

    for filename in os.listdir(SSH_DIR):
        # Sincronizar apenas arquivos conhecidos ou novos tokens
        if filename in files_to_sync or filename.endswith("-token") or filename.endswith(".env"):
            local_path = os.path.join(SSH_DIR, filename)
            if os.path.isfile(local_path):
                s3_path = f"{S3_PREFIX}{filename}"
                print(f"Subindo {filename} -> {s3_path}...")
                try:
                    s3.upload_file(local_path, BUCKET_NAME, s3_path)
                    print(f"  OK: {filename} sincronizado.")
                except Exception as e:
                    print(f"  Erro ao subir {filename}: {e}")

if __name__ == "__main__":
    sync_to_civo()
