#!/bin/bash -e

# Resets a user's password
# Except for the special shared account,
# the user will be asked for a password on next login

if [ "$#" -ne 2 ]; then
    echo "usage: $0 device username"
    echo "(run eos-list-users to see a list of devices and usernames)"
    exit 1
fi
DEVICE=$1
USERNAME=$2

USERID=$(id -u)
if [ "$USERID" != "0" ]; then
    echo "Program requires superuser privileges"
    exit 1
fi

if [ $USERNAME = root ]; then
    echo "Resetting root password not allowed"
    exit 1
elif [ $USERNAME = shared ]; then
    # For the shared account, set the change date (days since Jan 1, 1970)
    # to today (so that user will not be asked to set a password)
    DATE=$((`date +"%s"` / 86400))
else
    # Any other user should set the password on next login
    DATE=0
fi

MOUNT=`mktemp -d`
LOOPBACK=

cleanup() {
    set +e

    umount "$MOUNT"

    if [ -n "$LOOPBACK" ]; then
        losetup -d "$LOOPBACK"
        udevadm settle

        umount "$MOUNT"
    fi

    rmdir "$MOUNT"
}
trap cleanup EXIT

mount $DEVICE $MOUNT

# Check if it's a Windows partition with a dual-boot Endless OS image
LABEL=$(lsblk -o LABEL --raw --nodeps --noheadings "$DEVICE")
ENDLESS_IMG="$MOUNT/endless/endless.img"
if [ "$LABEL" != "ostree" ] && [ -e "$ENDLESS_IMG" ]; then
    if [ -e "$MOUNT/endless/live" ]; then
        echo "$DEVICE is a read-only live USB; refusing to change passwords" >&2
        exit 1
    fi

    # Time for a loopback mount!
    LOOPBACK=$(losetup --find --show "$ENDLESS_IMG")
    partprobe "$LOOPBACK"

    # Find the ostree partition
    DEVICE=$(lsblk --raw --paths -o LABEL,NAME "$LOOPBACK" |
             awk '/^ostree / { print $2 }')
    if [ -z "$DEVICE" ]; then
        echo "Cannot find Endless OS partition in $ENDLESS_IMG" >&2
        exit 1
    fi

    mount "$DEVICE" "$MOUNT"
fi

CURRENT=$(ostree admin --sysroot=$MOUNT --print-current-dir)
sed -i "s/$USERNAME:[^:]*:[^:]*:/$USERNAME::$DATE:/" $CURRENT/etc/shadow
