#!/usr/bin/env bash
# DyzineFrame first-time Pi install (OS packages, pip deps, desktop, harden).
#
# Preferred name: install.sh (this file is also install_script.sh for legacy).
# Run as topbox from the tree that should become ~/DyzineFrame, or from live:
#
#   cd ~/DyzineFrame && bash install.sh
#   # or: bash install_script.sh
#
# File sync from Dropbox is separate: ~/EtherGold/sync/pull_all_from_dropbox.sh
# EtherGold tip rebuild is separate: ~/EtherGold/sync/update.sh

set -euo pipefail

if [[ "${EUID}" -eq 0 ]]; then
  echo "DO NOT RUN THIS SCRIPT AS ROOT!" >&2
  exit 1
fi

echo "=== DyzineFrame install (first-time bootstrap) ==="

# shellcheck source=pi_python_policy.sh
_DF_HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "${_DF_HERE}/pi_python_policy.sh"

echo "Installing OS deps (no full-upgrade — Bookworm python3.11 must stay)..."
df_apt_install_df_deps
sudo timedatectl set-ntp true || true
if [[ -f "${_DF_HERE}/sync/install_http_date_sync.sh" ]]; then
  echo "Installing HTTPS Date clock fallback (12h timer)..."
  bash "${_DF_HERE}/sync/install_http_date_sync.sh" || echo "WARN: HTTP date timer not installed (need sudo -n)" >&2
fi
if [[ -f "${_DF_HERE}/sync/install_hs_out_idle.sh" ]]; then
  echo "Installing Pi HS OUT idle-low (BCM10/11)..."
  bash "${_DF_HERE}/sync/install_hs_out_idle.sh" || echo "WARN: HS OUT idle not installed (need sudo -n)" >&2
fi
df_require_supported_python

echo "Installing Python packages (no version roll)..."
df_pip_ensure_df_modules

# Seed ~/DyzineFrame only when missing (first clone from a USB/copy cwd).
if [[ ! -d "${HOME}/DyzineFrame" ]]; then
  echo "Creating ~/DyzineFrame from $(pwd)..."
  cp -a ./ "${HOME}/DyzineFrame"
fi

DF="${HOME}/DyzineFrame"
bash "${DF}/ensure_pi_desktop.sh"

if [[ -f "${DF}/install_pogcc_permdev.sh" ]]; then
  echo "Installing POG-CC PermDevMapper (/dev/ser_DT1 → /dev/pogcc)..."
  bash "${DF}/install_pogcc_permdev.sh" || {
    echo "WARN: PermDevMapper install failed — DyzineFrame can fall back to /dev/ttyUSB0" >&2
  }
fi

echo ""
echo "DyzineFrame install complete."
echo "  Desktop: autostart + wallpaper + dialog harden applied."
echo "  P3 port: /dev/pogcc via pogcc-permdev.service (status: /run/dyzineframe/pogcc_link.status)."
echo "  Later code pulls:  cd ~/EtherGold/sync && bash pull_all_from_dropbox.sh"
echo "  Dep refresh only:  cd ~/DyzineFrame && bash update.sh"
echo "  EtherGold tip:     cd ~/EtherGold/sync && bash update.sh"
