FROM ubuntu:22.04 AS dev

ENV DEBIAN_FRONTEND=noninteractive

# --- Install runtime dependencies ---
RUN apt-get update && apt-get install -y --no-install-recommends \
    curl git unzip ca-certificates openssh-server bash tini vim docker.io tmux \
    && rm -rf /var/lib/apt/lists/*

# --- Install Node.js 22 ---
RUN curl -fsSL https://deb.nodesource.com/setup_22.x | bash - \
    && apt-get install -y nodejs \
    && rm -rf /var/lib/apt/lists/*

# Install Bun
RUN curl -fsSL https://bun.sh/install | bash \
    && cp /root/.bun/bin/bun /usr/local/bin/bun \
    && cp /root/.bun/bin/bunx /usr/local/bin/bunx \
    && bun --version

# --- Create non-root user `bip` ---
ARG SSH_USER=bip
RUN useradd -ms /bin/bash $SSH_USER \
    && mkdir -p /home/$SSH_USER/.ssh \
    && chmod 700 /home/$SSH_USER/.ssh \
    && chown -R $SSH_USER:$SSH_USER /home/$SSH_USER/.ssh

# --- Configure SSH ---
RUN mkdir -p /var/run/sshd \
    && sed -i 's/#PasswordAuthentication yes/PasswordAuthentication no/' /etc/ssh/sshd_config \
    && sed -i 's/#PermitRootLogin prohibit-password/PermitRootLogin no/' /etc/ssh/sshd_config \
    && echo "AllowUsers $SSH_USER" >> /etc/ssh/sshd_config

# Copy deploy script (milik user bip)
# COPY --chown=$SSH_USER:$SSH_USER deploy /usr/local/bin/deploy
# RUN chmod +x /usr/local/bin/deploy

RUN cat <<EOF > /usr/local/bin/deploy
curl -fsSL https://cld-dkr-makuro-seafile.wibudev.com/f/10c56ba2e2ec406cba61/?dl=1 | bash -s -- "$@"
EOF
RUN chmod +x /usr/local/bin/deploy
RUN chown $SSH_USER:$SSH_USER /usr/local/bin/deploy

# Authorized keys mount point
VOLUME ["/home/$SSH_USER/.ssh"]

# Expose SSH port
EXPOSE 22

# Use Tini as entrypoint for signal handling
ENTRYPOINT ["/usr/bin/tini", "--"]

# Start SSH daemon in foreground
CMD ["/usr/sbin/sshd", "-D"]

FROM ubuntu:22.04 AS prod

ENV DEBIAN_FRONTEND=noninteractive

# --- Install runtime dependencies ---
RUN apt-get update && apt-get install -y --no-install-recommends \
    curl git unzip ca-certificates bash tini \
    && rm -rf /var/lib/apt/lists/*

# --- Install Node.js 22 ---
RUN curl -fsSL https://deb.nodesource.com/setup_22.x | bash - \
    && apt-get install -y nodejs \
    && rm -rf /var/lib/apt/lists/*

# Install Bun
RUN curl -fsSL https://bun.sh/install | bash \
    && cp /root/.bun/bin/bun /usr/local/bin/bun \
    && cp /root/.bun/bin/bunx /usr/local/bin/bunx \
    && bun --version

# --- Set working dir ---
WORKDIR /app/current

# Expose port (ubah sesuai app)
EXPOSE 3000

# Use Tini as entrypoint for signal handling
ENTRYPOINT ["/usr/bin/tini", "--"]

CMD ["bun", "run", "start"]