#!/bin/bash

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

HOSTNAME="$1"

SS="$(brew --prefix)/opt/util-linux/bin/setsid"

if [[ ! -e $SS ]]; then
    brew install util-linux
fi

SSH_OPTIONS="-oLogLevel=error"
SSH_OPTIONS="${SSH_OPTIONS} -oStrictHostKeyChecking=no"
SSH_OPTIONS="${SSH_OPTIONS} -oUserKnownHostsFile=/dev/null"

echo 'echo raspberry' > /tmp/defaultpw.sh
chmod 777 /tmp/defaultpw.sh
export SSH_ASKPASS="/tmp/defaultpw.sh"
export DISPLAY=nope
tar -c ./root | $SS ssh $SSH_OPTIONS pi@raspberrypi.local "
    DEBIAN_FRONTEND=noninteractive
    sudo hostname $HOSTNAME &&
    echo $HOSTNAME | sudo tee /etc/hostname &&
    sudo apt update &&
    sudo apt install -y rsync bash &&
    sudo mkdir -p /tmp/setup &&
    sudo chmod ugoa+rx /tmp/setup &&
    cd /tmp/setup &&
    sudo tar xvf - &&
    sudo rsync -avP /tmp/setup/root/ / &&
    reboot ;
"
