#!/usr/bin/env bun

import { $ } from "bun"

const defaultUser = process.env.USER ?? "corey"
const PI_HOST = process.env.PI_HOST ?? "phone.local"
const PI_DIR = process.env.PI_DIR ?? `/home/${defaultUser}/phone`

// Parse command line arguments
const shouldBootstrap = process.argv.includes("--bootstrap")

console.log(`🧪 Run basic tests...\n`)

await $`bun run typecheck`

console.log(`📦 Deploying to ${PI_HOST}...\n`)

// Create directory on Pi
console.log("Creating directory on Pi...")
await $`ssh ${PI_HOST} "mkdir -p ${PI_DIR}"`

// Sync files from . directory to Pi (only transfers changed files)
console.log("Syncing files from . directory...")
await $`rsync -avz --delete  --exclude-from='../.gitignore' --exclude='.git' . ${PI_HOST}:${PI_DIR}/`

// Make all TypeScript files executable
console.log("Making scripts executable...")
await $`ssh ${PI_HOST} "chmod +x ${PI_DIR}/scripts/*"`

console.log("\n✓ Files deployed!\n")

// Run bootstrap if requested
if (shouldBootstrap) {
  console.log("🍞 Running bootstrap-bun on Pi...\n")
  await $`ssh ${PI_HOST} "bash ${PI_DIR}/scripts/bootstrap-bun.sh"`

  console.log("Running bootstrap on Pi...\n")
  await $`ssh ${PI_HOST} "cd ${PI_DIR} && sudo bun ${PI_DIR}/scripts/bootstrap.ts ${PI_DIR}"`
}

// make console beep
await $`afplay /System/Library/Sounds/Blow.aiff`

// Always set up services on every deploy
console.log("Setting up services...")
await $`ssh ${PI_HOST} "sudo bun ${PI_DIR}/scripts/setup-services.ts ${PI_DIR}"`
console.log("✓ Services configured and running\n")

console.log(`
✓ Deploy complete!

Access via WiFi at http://phone.local
The Pi is discoverable as "phone-setup"
`)
