ARG HASS_VERSION=latest

FROM homeassistant/home-assistant:$HASS_VERSION

RUN apk add --update-cache zbar mysql-client \
  && rm -rf /var/cache/apk/*

# Check if root
# If running as root, remove setuid and setgid flags of everything
# Then add a hass user and make that the owner of /config
# Finally, make pip install to user folders
RUN python3 -c 'import os; assert os.geteuid() == 0, "Already non-root! Skip changing user"' \
  && find / -xdev -type f -perm /u+s -exec chmod -c u-s {} \; \
  && find / -xdev -type f -perm /g+s -exec chmod -c g-s {} \; \
  && adduser -D hass \
  && addgroup hass dialout \
  && chown hass /config \
  && mkdir -p ~hass/.config/pip \
  && chown hass ~hass/.config \
  && chown hass ~hass/.config/pip \
  && echo -e '[install]\nuser = yes' > ~hass/.config/pip/pip.conf \
  && mkdir -p ~hass/.local/lib \
  && chown hass ~hass/.local \
  && chown hass ~hass/.local/lib

COPY wait-for-db.sh /home/hass/wait-for-db.sh
RUN chmod +x /home/hass/wait-for-db.sh

USER hass

# Make /config persistent even if not mounted
VOLUME /config
# Make pip cache persistent
VOLUME /home/hass/.local/lib
WORKDIR /config
# Export default port for use with routers like traefik
EXPOSE 8123/tcp

CMD ["/home/hass/wait-for-db.sh", "python3", "-m", "homeassistant", "-v", "--config", "/config"]

HEALTHCHECK CMD curl http://localhost:8123/ || exit 1
