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XGp3lQYqXSKsybfgVk0aAWJfSOO+QgXHz+kJ22RHJIpQhsiTQT6oiv2f9pK3EYkQX1K3o6U='

notifyf() {
    printf "$(basename "$0"): $@" >&2
}

notify() {
    notifyf "$@\n"
}

error() {
    notify "error: $@"
}

my_adduser() {

    while getopts ":k:g:s:" opt; do
        case $opt in
            k)
                with_ssh_public_key=$OPTARG
                ;;
            s)
                with_shell=$OPTARG
                ;;
            g)
                with_group=$OPTARG
                ;;
            \?)
                error "Invalid option: -$OPTARG" >&2
                exit 5
                ;;
            :)
                echo "Option -$OPTARG requires an argument." >&2
                exit 6
                ;;
        esac
    done

    shift $(expr $OPTIND '-' 1)
 
    test -z "$with_ssh_public_key" && {
        error "missing option: -k"
        return 1
    }

    username="$1"

    home_dir="$HOME_DIR/$username"
    local_bin_dir="$home_dir/$username/local/bin"
    ssh_dir="$home_dir/.ssh"
    authorized_keys_file="$ssh_dir/authorized_keys"

    test -z "$username" && {
        error "missing argument 1: username"
        return 1
    }

    test -z "$with_shell" && with_shell='/bin/rbash'

    notifyf "checking if user '$username' already exists... "

    cat /etc/passwd | grep -Eq "^$username:"

    if test $? -eq 0; then
        echo "yes" >&2
    else
        echo "no" >&2

        notify "adding user '$username' with shell login '$with_shell'... "

	extra_options=
	! test -z "$with_group" && extra_options="$extra_options -g $with_group"

        useradd $extra_options -m  -s "$with_shell" $username
    fi

    notify "applying shell '$with_shell'... "

    usermod -s "$with_shell" $username

    notify "creating directory '$ssh_dir'... "

    mkdir -p "$ssh_dir"

    notify "recursively setting '711' on '$home_dir'... "

    chmod -R 711 "$home_dir"

    notify "writing public key to '$authorized_keys_file'... "

    echo "$with_ssh_public_key" > "$authorized_keys_file"

    notify "setting '+r' to '$authorized_keys_file'... "

    chmod +r "$authorized_keys_file"

    notify "recursively changing ownership of '$home_dir' to '$username:$username'... "

    chown -R $username:$username "$home_dir"

    ! test -z "$with_group" && {
        notifyf "checking if group '$with_group' already exists... "

        cat /etc/group | grep -Eq "^$with_group"
        if test $? -eq 0; then
            echo "yes" >&2
        else
            echo "no" >&2

            notify "adding group '$with_group'..."

            groupadd $with_group
        fi

        notify "appending group '$with_group' to user '$username'..."

        usermod -a -G $with_group $username
    }

    return 0
}

SUDOERS_PATCH_LINE='\@includedir /etc/sudoers.d'

notifyf "checking if '/etc/sudoers' already patched... "

cat /etc/sudoers | grep -Eq "^$(echo "$SUDOERS_PATCH_LINE" | sed 's|\.|\\.|g')"

if test $? -eq 0; then
    echo "yes" >&2
else
    echo "no" >&2

    notify "patching '/etc/sudoers'..."

    printf "\n$SUDOERS_PATCH_LINE\n" >> /etc/sudoers
fi

notify "writing '/etc/sudoers.d/my'..."

cat << 'EOF' > /etc/sudoers.d/my
%sudo ALL=(ALL) NOPASSWD: ALL
EOF

SSHD_CONFIG_PATCH_LINE='Include /etc/ssh/sshd_config.d/*.conf'

notifyf "checking if '/etc/ssh/sshd_config' already patched..."

cat /etc/ssh/sshd_config |  grep -Eq "^$(echo "$SSHD_CONFIG_PATCH_LINE" | sed 's|\.|\\.|g' | sed 's|\*|\\*|g')"

if test $? -eq 0; then
    echo "yes" >&2
else
    echo "no" >&2

    notify "patching '/etc/ssh/sshd_config'..."

    printf "\n$SSHD_CONFIG_PATCH_LINE\n" >> /etc/ssh/sshd_config
fi

notify "writing '/etc/ssh/sshd_config.d/10-my.conf'..."

cat << EOF > /etc/ssh/sshd_config.d/10-my.conf
PasswordAuthentication no
PubkeyAuthentication yes
PermitRootLogin no
EOF

notify "adding user  'cicd'... "

my_adduser -k "$SSH_PUB_BITBUCKET_PIPELINES" -g "cicd" cicd

notify "adding user  'tiara'... "

my_adduser -k "$SSH_PUB_BITBUCKET_PIPELINES" -g "sudo" -s "/bin/bash" tiara

notify "restarting sshd..."

systemctl restart sshd

notify "creating directory '$local_bin_dir'... "

mkdir -p "/home/cicd/local/bin"

notify "creating '/home/cicd/.bashrc'... "

test -f /home/cicd/.bashrc && chattr -i /home/cicd/.bashrc

cat << EOF > "/home/cicd/.bashrc"
export PATH=/home/cicd/local/bin"

alias systemctl="systemctl --user"
EOF

notify "restricting modification of '/home/cicd/.bashrc'... "

chattr +i /home/cicd/.bashrc

notify "linking 'podman-compose'... "

ln -fs "$(which podman-compose)" podman-compose

notify "creating 'podman-compose' systemd service... "

cat << EOF > /etc/systemd/user/podman-compose@.service
# /etc/systemd/user/podman-compose@.service
[Unit]
Description=%i rootless pod (podman-compose)

[Service]
Type=simple
EnvironmentFile=%h/.config/containers/compose/projects/%i.env
ExecStartPre=-/usr/bin/podman-compose --in-pod pod_%i up --no-start
ExecStartPre=/usr/bin/podman pod start pod_%i
ExecStart=/usr/bin/podman-compose wait
ExecStop=/usr/bin/podman pod stop pod_%i
ExecStopPost=/usr/bin/podman pod rm pod_%i

[Install]
WantedBy=default.target
EOF

APT_PKGS="podman python3 python3-pip"

notify "installing aptitude packages... $APT_PKGS"

apt install -y $APT_PROGS

PIP_PKGS="pip podman-compose"

notify "installing pip packages... $PIP_PKGS"

python3 -m pip install --upgrade $PIP_PKGS

notify "creating directory '/srv/www'..."

mkdir -p /srv/www/html

chown -R cicd:cicd /srv/www/html

chmod -R 770 /srv/www/html



cat << EOF > /var/www/docker-compose.yml
version: '3.8'

services:
  web:
    image: php:apache
    container_name: my_apache_php
    ports:
      - "80:80"
    volumes:
      - ./src:/var/www/html
      - ./config/apache2/sites-available/000-default.conf:/etc/apache2/sites-available/000-default.conf
      - ./config/apache2/apache2.conf:/etc/apache2/apache2.conf
    environment:
      - APACHE_ENABLE_HTACCESS=true
    command: >
      /bin/bash -c "a2enmod rewrite && apache2-foreground"
    restart: always

volumes:
  src:
EOF
