#!/bin/bash

# we verify the presence of the PASSWORD variable using env,
# as it can also have an empty string value
if ! env | grep PASSWORD &>/dev/null; then
    echo "You must set the PASSWORD environment variable."
    exit 1
fi

# make sure root and admin users exist in shadow file
touch /data/etc/shadow
chmod go-rwx /data/etc/shadow
if ! grep root /data/etc/shadow &>/dev/null; then
    echo 'root::::::::' >> /data/etc/shadow
fi
if ! grep admin /data/etc/shadow &>/dev/null; then
    echo 'admin::::::::' >> /data/etc/shadow
fi

# remove shadow backups
rm -f /data/etc/shadow+
rm -f /data/etc/shadow-

# set root and admin passwords (admin is just an alias for root)

echo -en "${PASSWORD}\n${PASSWORD}\n" | passwd -a md5 &>/dev/null # root
echo -en "${PASSWORD}\n${PASSWORD}\n" | passwd -a md5 admin &>/dev/null # admin

sed -r -i 's/root:([^:]+):[[:digit:]]+:/root:\1::/' /data/etc/shadow # removes pwd expiration
sed -r -i 's/admin:([^:]+):[[:digit:]]+:/admin:\1::/' /data/etc/shadow # removes pwd expiration

# call admin password hooks in /etc/adminpasswd.d
if [ -d /etc/adminpasswd.d ]; then
    for script in /etc/adminpasswd.d/*; do
        test -x ${script} && ${script}
    done
fi

sync
