#!/bin/sh
# PROJECT DOUSE - clone.sh : 1:1 images of the system + data partitions into the user store.
#   sh /mnt/us/clone.sh          -> image p8, p9, p5, then verify
#   sh /mnt/us/clone.sh check    -> verify existing images only (no dd)
# Every partition is READ. The only writes are the image files on p10 (the user store).
# Log: /mnt/us/clone.log

MODE=${1:-clone}
DST=/mnt/base-us            # the user store itself, bypassing the fsp/fuse layer
LOG=/mnt/us/clone.log
: > "$LOG"
say()  { echo "$@" | tee -a "$LOG"; }
sz()   { ls -l "$1" 2>/dev/null | awk '{print $5}'; }
psz()  { awk -v p="$1" '$4==p {print $3*1024}' /proc/partitions; }   # partition size in bytes
secs() { date +%s; }

say "=== DOUSE CLONE mode=$MODE $(date) ==="
say "uname: $(uname -a)"
say "battery: $(cat /sys/class/power_supply/*/capacity 2>/dev/null | head -1)%"
say "--- partitions of interest ---"
grep -E 'mmcblk0p(5|8|9|10)$' /proc/partitions | tee -a "$LOG"
say "--- how they are mounted right now ---"
grep -E 'mmcblk0p(5|8|9)|loop/0 |/dev/root ' /proc/mounts | tee -a "$LOG"
say "--- user store free space (KB) ---"
df -k "$DST" | tee -a "$LOG"

FREE=$(df -k "$DST" | awk 'NR==2 {print $4}')
NEED=2300000
if [ "$MODE" = "clone" ] && [ "${FREE:-0}" -lt "$NEED" ]; then
  say "NO-GO: need ~${NEED} KB free in the user store, have ${FREE:-?} KB"; exit 1
fi

# keep the device awake for the duration (harmless if the property does not exist)
lipc-set-prop com.lab126.powerd preventScreenSaver 1 >/dev/null 2>&1 || true

image_part() {   # image_part <partition> <image name>
  P=$1; IMG=$DST/$2
  if [ -f "$IMG" ]; then
    say "  existing $IMG kept as $IMG.old"; mv -f "$IMG" "$IMG.old"
  fi
  say ""; say "### imaging $P -> $IMG"
  sync; sleep 2                      # flush stock's dirty pages so the copy is as fresh as possible
  T0=$(secs)
  dd if=/dev/$P of="$IMG" bs=4194304 >>"$LOG" 2>&1
  RC=$?
  T1=$(secs)
  say "  dd exit $RC, $((T1 - T0)) s, size $(sz "$IMG") (expected $(psz $P))"
  if [ "$RC" -ne 0 ] || [ "$(sz "$IMG")" != "$(psz $P)" ]; then
    say "FAIL: $P image is incomplete"; return 1
  fi
  return 0
}

if [ "$MODE" = "clone" ]; then
  image_part mmcblk0p8 p8.img || exit 1
  image_part mmcblk0p9 p9.img || exit 1
  image_part mmcblk0p5 p5.img || exit 1
  image_part mmcblk0boot1 boot1.img
  image_part mmcblk0boot0 boot0.img
  sync
fi

say ""; say "### verify p8 (read-only partition: md5 must match exactly)"
T0=$(secs)
M_DEV=$(md5sum /dev/mmcblk0p8 | awk '{print $1}')
M_IMG=$(md5sum "$DST/p8.img" | awk '{print $1}')
say "  dev  $M_DEV"
say "  img  $M_IMG   ($(( $(secs) - T0 )) s)"
if [ "$M_DEV" = "$M_IMG" ]; then say "  OK: p8.img is byte-exact"; else say "  FAIL: p8.img differs from p8 - re-run"; fi

E2FSCK=""
for c in /sbin/e2fsck /usr/sbin/e2fsck /sbin/fsck.ext4 /usr/sbin/fsck.ext4 /sbin/fsck.ext3; do
  [ -x "$c" ] && E2FSCK=$c && break
done
say ""; say "### fsck the copies of the live partitions (journal replay is expected; exit 0/1 good, 4/8 bad)"
if [ -z "$E2FSCK" ]; then
  say "  no e2fsck on the device - run on PC instead: e2fsck -fy p9.img ; e2fsck -fy p5.img"
else
  for i in p9 p5; do
    say "--- $E2FSCK -fy $DST/$i.img"
    $E2FSCK -fy "$DST/$i.img" >>"$LOG" 2>&1
    RC=$?
    case $RC in
      0) say "  $i.img: clean (exit 0)";;
      1) say "  $i.img: journal replayed / fixed, now clean (exit 1) - normal for a live copy";;
      *) say "  $i.img: PROBLEM (exit $RC) - re-run the clone";;
    esac
  done
fi

lipc-set-prop com.lab126.powerd preventScreenSaver 0 >/dev/null 2>&1 || true
say ""; say "### result"
ls -l "$DST"/p8.img "$DST"/p9.img "$DST"/p5.img 2>&1 | tee -a "$LOG"
df -k "$DST" | tee -a "$LOG"
say "=== DONE $(date) - upload /mnt/us/clone.log ==="
