#!/bin/bash
exit 1

# the following assumes you are already running alpine
# and want to set up an alpine chroot at /rw

rm -rf /rw
apk -U --root /rw --initdb add alpine-base || true
cat > /rw/etc/apk/repositories <<'EOF'
http://mirror.leaseweb.com/alpine/v3.15/main
http://mirror.leaseweb.com/alpine/v3.15/community
EOF
cat > /rw/etc/apk/repositories <<'EOF'
/home/ed/packages/main
/home/ed/packages/community
http://mirror.leaseweb.com/alpine/edge/main
http://mirror.leaseweb.com/alpine/edge/community
EOF
tar -c -C / /etc/apk/keys/ | tar -x -C /rw/
apk -U --root /rw --initdb add alpine-base

cat > /rw/enter <<'EOF'
#!/bin/sh
set -e
cd "$(dirname "$0")"
cp /etc/resolv.conf etc/
mount | grep -q "on /rw/sys" || {
  mount -t proc none proc
  mount -o bind /sys sys
  mount -o bind /dev dev
  # mkdir -p /rw/home/ed
  # mount -o bind /home/ed /rw/home/ed
}
chmod 777 dev/shm
chroot . /bin/sh -l
umount dev sys proc
EOF
chmod 755 /rw/enter
/rw/enter

# you can stop at this point
# unless you intend to build apk files (alpine packages)

apk add alpine-sdk sudo
adduser -s /bin/ash -D ed
addgroup ed abuild
cat >> /etc/sudoers <<'EOF'
ALL ALL=(ALL) NOPASSWD: ALL
EOF

cat >> /etc/abuild.conf <<'EOF'
PACKAGER="John Smith <changeme@ocv.me>"
MAINTAINER="$PACKAGER"
EOF
sed -ri 's/export JOBS=2/export JOBS=4/' /etc/abuild.conf

sudo mkdir -p /var/cache/distfiles
sudo chmod a+w /var/cache/distfiles

# automatically builds the most recently modified APKBUILD
cp $(which find) /rw/find
cat > /rw/usr/bin/wabuild <<'EOF'
cd "$(/find ~/aports/testing/ -name APKBUILD -printf '%T@ %p\n' | sort -n | tail -n 1 | sed -r 's/[^ ]* //;s/.APKBUILD$//')"; ot=0; abuild checksum; while true; do t=$(stat -c%Y APKBUILD); [[ "$t" == "$ot" ]] && { read -u1 -r -t 0.2 && ot=0; continue; }; ot=$t; abuild -rK && break; echo '@@@'; pwd; ls src/*; done; echo; tar -tvf "$(/find ~/packages/ -type f -iname \*.apk -printf '%T@ %p\n' | grep -vE -- '-(dbg|dev|doc)-' | sort -n | sed -r 's/[^ ]* //' | tail -n 1 | tee /dev/shm/apkpath)"; cat /dev/shm/apkpath
EOF
cat > /rw/usr/bin/vabuild <<'EOF'
cd "$(/find ~/aports/testing/ -name APKBUILD -printf '%T@ %p\n' | sort -n | tail -n 1 | sed -r 's/[^ ]* //;s/.APKBUILD$//')"; ot=0; abuild checksum; while true; do t=$(stat -c%Y APKBUILD); [[ "$t" == "$ot" ]] && { read -u1 -r -t 0.2 && ot=0; continue; }; ot=$t; abuild -rK && break; echo '@@@'; pwd; ls src/*; done; echo; /find ~/packages/ -type f -iname \*.apk -newer APKBUILD | sort | while IFS= read -r x; do printf '\n\033[35m%s\033[0m\n' "$x"; tar -tvf "$x"; done
EOF
chmod 755 /rw/usr/bin/wabuild /rw/usr/bin/vabuild

su ed
abuild-keygen -nai
alias ll='ls -al'
alias vim='vi'
mkdir -p ~/aports
cd ~/aports
