#!/bin/bash

set -euo pipefail

# ---------------------------------------------------------------------------
LOG_DIR="/home/hydrohub/HydroHub"
LOG_FILE="${LOG_DIR}/expandFileSys.log"

DEVICE="/dev/mmcblk0"
P2="${DEVICE}p2"

TAIL_THRESH_MB=10
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
SRC_HELPER="${SCRIPT_DIR}/resize2fs_once"
DST_HELPER="/etc/init.d/resize2fs_once"
# ---------------------------------------------------------------------------

# ---------- 1. How much space is past the partition table? ------------------
UNALLOC_MB=$(
  parted -m "${DEVICE}" unit MB print free \
  | awk -F: '/Free Space/ {gsub("MB","",$4); size=$4} END{print int(size)}'
)

# ---------- 2. Is the filesystem smaller than the partition? ----------------
PART_BYTES=$(blockdev --getsize64 "${P2}")
PART_MB=$(( PART_BYTES / 1024 / 1024 ))
FS_BYTES=$(df --block-size=1 / | awk 'NR==2 {print $2}')
GAP_MB=$(( (PART_BYTES - FS_BYTES) / 1024 / 1024 ))
FS_GAP_THRESHOLD_MB=$(( PART_MB / 50 ))   # 2 %
(( FS_GAP_THRESHOLD_MB < 10 )) && FS_GAP_THRESHOLD_MB=10

NEED_RESIZE=false
if (( UNALLOC_MB > TAIL_THRESH_MB )); then
    NEED_RESIZE=true                       # tail gap detected
elif (( GAP_MB > FS_GAP_THRESHOLD_MB )); then
    NEED_RESIZE=true                       # filesystem still smaller
fi

# ---------- 3. Exit quietly if nothing to do --------------------------------
if [ "${NEED_RESIZE}" = false ]; then
    exit 0
fi

# ---------- 4. From here on we **log** everything ---------------------------
exec > >(tee -a "${LOG_FILE}") 2>&1
echo "===== $(date '+%F %T')  expandFileSys.sh started ====="
echo "Unallocated tail space  : ${UNALLOC_MB} MB"
echo "Partition-filesys gap   : ${GAP_MB} MB (limit ${FS_GAP_THRESHOLD_MB} MB)"
echo "⇒  Scheduling filesystem expansion"

# ---------- 5. Ensure exactly one init= token -------------------------------
sed -Ei 's@ *init=/\S+/init_resize\.sh@@'  /boot/cmdline.txt
grep -q 'init=/usr/lib/raspi-config/init_resize.sh' /boot/cmdline.txt \
  || sed -i 's@$@ init=/usr/lib/raspi-config/init_resize.sh@' /boot/cmdline.txt
echo "Patched /boot/cmdline.txt"

# ---------- 6. Install helper and enable once -------------------------------
tr -d '\r' < "${SRC_HELPER}" > "${DST_HELPER}"
chmod 0755 "${DST_HELPER}"
systemctl enable resize2fs_once.service
echo "Installed and enabled ${DST_HELPER}"

echo "Expansion staged – system will reboot in 10 seconds..."
sleep 10
reboot
