#!/bin/bash

THISDIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null 2>&1 && pwd )"

function die {
    echo "$1" > /dev/stderr
    exit 1
}

function info {
    echo "$1" > /dev/stderr
}

if [ "$#" -ne 1 ]; then
    die "usage: $0 <newhostname>"
fi

NEWHOSTNAME="$1"

function doinstall {

    # assumes osx
    [[ "$(uname -s)" != "Darwin" ]] && die "need osx"


    TARGET="/Volumes/boot"

    if [[ ! -e "$TARGET/LICENCE.broadcom" ]]; then
        die "cant find rpi boot dir"
    else
        info "rpi boot dir found at $TARGET"
    fi

    # copy root overlay into FAT /boot partition
    rsync -avP "$THISDIR/root.overlay/" "$TARGET/root.overlay/"

    # set hostname in overlay:
    mkdir -p $TARGET/root.overlay/etc
    echo "$NEWHOSTNAME" > "$TARGET/root.overlay/etc/hostname"
    cat >> $TARGET/root.overlay/etc/hosts <<EOF
127.0.0.1	localhost
::1		localhost ip6-localhost ip6-loopback
ff02::1		ip6-allnodes
ff02::2		ip6-allrouters

127.0.1.1	$NEWHOSTNAME
EOF

    rsync -avP "$THISDIR/rc.local.txt" "$TARGET/rc.local.txt"

    # fixed in my image
    # 2019-09-26-raspbian-buster-lite-patched-rclocal-noresizeroot.zip
    #info "disabling partition resize"
    #sed -i '' -e 's/init=[^[:space:]]*//' "$TARGET/cmdline.txt"

    sync
    diskutil eject $TARGET
}

doinstall
