#!/bin/sh
#set -e
set -x
TTYD_ARGS="login"

# Check if this is the container's first run
# Create user account
userdel $USERNAME
adduser -D --shell=/bin/sh $USERNAME

# Create restricted shell wrapper
echo "#!/bin/sh
    trap '' SIGINT
    cd /home/$USERNAME
    export PATH=/home/$USERNAME:/bin:/usr/bin
    while :
    do
        rm -rf /home/$USERNAME/*
        clear
        echo \"*** Starting Minishell ***\"
        /bin/minishell
    done" > /home/$USERNAME/.runshell.sh
chmod 001 /home/$USERNAME/.runshell.sh
echo "./.runshell.sh" >> /home/$USERNAME/.profile

# Add password
echo "$USERNAME:$PASSWORD" | chpasswd

# iptables -A OUTPUT -m owner --uid-owner $(id -u $USERNAME) -j DROP 2>/dev/null || true

# NOW block access to everything outside home (after setup is done)
chmod -R 700 /root /etc /usr /var /opt
chmod +rx /usr
chmod -R +rx /usr/bin
chmod -R 777 /home/$USERNAME


# Timezone (do this BEFORE blocking /etc access)
if [ ! -f /etc/.setup_complete ]; then
    CURRENT_TZ=$(cat /etc/timezone 2>/dev/null || echo "UTC")
    if [ "$TZ" != "$CURRENT_TZ" ]; then
        echo "Setting timezone to $TZ"
        [ -f /etc/localtime ] && rm /etc/localtime
        ln -s "/usr/share/zoneinfo/$TZ" /etc/localtime 2>/dev/null
        echo $TZ > /etc/timezone 2>/dev/null
    fi

    # Lock root
    passwd -l root 2>/dev/null

    # Mark setup complete
    touch /etc/.setup_complete
fi

# Auto login
[ "$AUTOLOGIN" = "true" ] && TTYD_ARGS="$TTYD_ARGS -f $USERNAME"

# Start ttyd
exec ttyd -W -m 5 -p 8006 $TTYD_ARGS
