| 1 | #!/bin/sh |
| 2 | set -eu |
| 3 | |
| 4 | REPOS_PATH="${FORGE_REPOS_PATH:-/data/repos}" |
| 5 | HOSTKEY_DIR="${FORGE_GIT_SSH_HOSTKEYS_PATH:-/data/git-ssh/hostkeys}" |
| 6 | GIT_USER="${GIT_USER:-git}" |
| 7 | SSH_PORT="${SSH_PORT:-2222}" |
| 8 | |
| 9 | mkdir -p "$REPOS_PATH" "$HOSTKEY_DIR" /var/run/sshd /home/"$GIT_USER"/.ssh |
| 10 | |
| 11 | RSA_KEY="$HOSTKEY_DIR/ssh_host_rsa_key" |
| 12 | if [ ! -f "$RSA_KEY" ]; then |
| 13 | echo "Generating git-ssh host key in $HOSTKEY_DIR (persists across redeploys) ..." |
| 14 | ssh-keygen -t rsa -b 4096 -f "$RSA_KEY" -N "" -C "forge-git-ssh" |
| 15 | fi |
| 16 | chmod 600 "$RSA_KEY" 2>/dev/null || true |
| 17 | |
| 18 | AUTH_KEYS="/home/$GIT_USER/.ssh/authorized_keys" |
| 19 | : >"$AUTH_KEYS" |
| 20 | chmod 600 "$AUTH_KEYS" |
| 21 | if [ -n "${FORGE_GIT_AUTHORIZED_KEYS:-}" ]; then |
| 22 | printf '%s\n' "$FORGE_GIT_AUTHORIZED_KEYS" >> "$AUTH_KEYS" |
| 23 | fi |
| 24 | if [ -f /etc/forge/authorized_keys ]; then |
| 25 | cat /etc/forge/authorized_keys >> "$AUTH_KEYS" |
| 26 | fi |
| 27 | |
| 28 | adduser -D -h "/home/$GIT_USER" -s /usr/bin/git-shell "$GIT_USER" 2>/dev/null || true |
| 29 | passwd -u "$GIT_USER" 2>/dev/null || true |
| 30 | su - "$GIT_USER" -s /bin/sh -c 'git config --global --add safe.directory "*"' 2>/dev/null || true |
| 31 | chown -R "$GIT_USER:$GIT_USER" /home/"$GIT_USER" |
| 32 | mkdir -p "$REPOS_PATH" |
| 33 | chown -R "$GIT_USER:$GIT_USER" "$REPOS_PATH" |
| 34 | |
| 35 | sync_repo_links() { |
| 36 | chown -R "$GIT_USER:$GIT_USER" "$REPOS_PATH" 2>/dev/null || true |
| 37 | find "$REPOS_PATH" -mindepth 1 -name '*.git' -type d | while read -r repo; do |
| 38 | rel=${repo#"$REPOS_PATH"/} |
| 39 | dest="/home/$GIT_USER/$(dirname "$rel")" |
| 40 | mkdir -p "$dest" |
| 41 | ln -sfn "$repo" "/home/$GIT_USER/$rel" |
| 42 | chown -h "$GIT_USER:$GIT_USER" "/home/$GIT_USER/$rel" 2>/dev/null || true |
| 43 | done |
| 44 | } |
| 45 | |
| 46 | sync_repo_links |
| 47 | |
| 48 | ( |
| 49 | while true; do |
| 50 | sleep 30 |
| 51 | sync_repo_links |
| 52 | done |
| 53 | ) & |
| 54 | |
| 55 | cat >/etc/ssh/sshd_config <<EOF |
| 56 | Port $SSH_PORT |
| 57 | Protocol 2 |
| 58 | HostKey $RSA_KEY |
| 59 | PasswordAuthentication no |
| 60 | PubkeyAuthentication yes |
| 61 | AuthorizedKeysFile .ssh/authorized_keys |
| 62 | PidFile /var/run/sshd/sshd.pid |
| 63 | Subsystem sftp internal-sftp |
| 64 | EOF |
| 65 | |
| 66 | exec /usr/sbin/sshd -D -e |
| 67 | |