#!/usr/bin/env bash
# Run on the provisioning HOST (root) to install PiShrink and dependencies.
# Enables shrinking backups in flash-emmc-on-connect.sh when SHRINK_BACKUP=1.
# PiShrink: https://github.com/Drewsif/PiShrink
#
# Offline install (when host has no internet):
#   1. On a machine with internet: curl -Lo pishrink.sh https://raw.githubusercontent.com/Drewsif/PiShrink/master/pishrink.sh
#   2. scp pishrink.sh root@HOST:/tmp/
#   3. On host: bash install-pishrink-on-host.sh /tmp/pishrink.sh
#
# Optional: PISHRINK_URL=... or pass path to local pishrink.sh as first argument.

set -e
PISHRINK_URL="${PISHRINK_URL:-https://raw.githubusercontent.com/Drewsif/PiShrink/master/pishrink.sh}"
LOCAL_PISHRINK="$1"

echo "Installing PiShrink dependencies (parted, e2fsprogs, xz-utils, ...)..."
if apt-get update 2>/dev/null && apt-get install -y wget parted gzip pigz xz-utils udev e2fsprogs 2>/dev/null; then
    echo "Dependencies installed."
else
    echo "Warning: apt install failed (e.g. host has no internet). Skipping packages."
    echo "PiShrink needs: parted, e2fsprogs; optional: gzip/pigz, xz-utils. Install them manually if missing."
    for cmd in parted resize2fs; do
        if ! command -v "$cmd" &>/dev/null; then
            echo "  Missing: $cmd — install with apt when the host has network, or use a local mirror."
        fi
    done
fi

if [[ -n "$LOCAL_PISHRINK" && -f "$LOCAL_PISHRINK" ]]; then
    echo "Using local PiShrink script: $LOCAL_PISHRINK"
    cp "$LOCAL_PISHRINK" /usr/local/bin/pishrink.sh
    chmod +x /usr/local/bin/pishrink.sh
    echo "PiShrink installed at /usr/local/bin/pishrink.sh"
elif command -v wget &>/dev/null && wget -q -O /usr/local/bin/pishrink.sh "$PISHRINK_URL" 2>/dev/null; then
    chmod +x /usr/local/bin/pishrink.sh
    echo "PiShrink installed at /usr/local/bin/pishrink.sh"
else
    echo "Could not download PiShrink (no wget or no network)."
    echo ""
    echo "Offline install:"
    echo "  1. On a machine WITH internet run:"
    echo "     curl -Lo pishrink.sh $PISHRINK_URL"
    echo "  2. Copy to host:"
    echo "     scp pishrink.sh root@YOUR_HOST:/tmp/"
    echo "  3. On the host run:"
    echo "     bash install-pishrink-on-host.sh /tmp/pishrink.sh"
    exit 1
fi

echo ""
echo "To shrink backups automatically, add to /opt/cm4-provisioning/env:"
echo "  SHRINK_BACKUP=1"
echo "  # optional: PISHRINK_COMPRESS=gz   or   PISHRINK_COMPRESS=xz"
