# shellcheck shell=dash

set -eu

AVAHIFILE=/etc/avahi/services/squid-deb-proxy.service

concat_file_from_dir() {
    # the .d directory
    DIR="$1"
    # the target file
    FILE="$2"
    # (optional) additional file append to $FILE
    ADDITIONAL_FILE_TO_CAT="${3-}"

    if [ -n "$ADDITIONAL_FILE_TO_CAT" ]; then
        cat "$ADDITIONAL_FILE_TO_CAT" >> "$FILE"
    fi

    for f in "$DIR"/*; do
        cat "$f" >> "$FILE"
    done
}

pre_start() {
    # generate pkg blocklist acl file
    PKG_BLOCKLIST_DIR=/etc/squid-deb-proxy/pkg-blocklist.d
    PKG_BLOCKLIST=/run/squid-deb-proxy/pkg-blocklist-regexp.acl
    concat_file_from_dir "$PKG_BLOCKLIST_DIR" "$PKG_BLOCKLIST"
    # postprocess for regexp format
    sed -i -r '/^#/d;/^$/d;s#(.*)#\/\1_.*\.deb$#g' $PKG_BLOCKLIST

    # generate mirror file
    MIRROR_DESTDOMAIN_DIR=/etc/squid-deb-proxy/mirror-dstdomain.acl.d
    MIRROR_DESTDOMAIN=/run/squid-deb-proxy/mirror-dstdomain.acl
    concat_file_from_dir "$MIRROR_DESTDOMAIN_DIR" "$MIRROR_DESTDOMAIN" "/etc/squid-deb-proxy/mirror-dstdomain.acl"

    # generate the allowed-networks file
    ALLOWED_NETWORKS_DIR=/etc/squid-deb-proxy/allowed-networks-src.acl.d
    ALLOWED_NETWORKS=/run/squid-deb-proxy/allowed-networks-src.acl
    concat_file_from_dir "$ALLOWED_NETWORKS_DIR" "$ALLOWED_NETWORKS" "/etc/squid-deb-proxy/allowed-networks-src.acl"

    if [ ! -d /var/cache/squid-deb-proxy/00 ]; then
        /usr/sbin/squid -z -N -f /etc/squid-deb-proxy/squid-deb-proxy.conf
    fi
}

post_start() {
    # create avahi service
    PORT=$(awk -F '[: ]' '/^http_port/ { print $NF; exit }' /etc/squid-deb-proxy/squid-deb-proxy.conf)
    if [ -n "$PORT" ] && [ -d /etc/avahi/services/ ]; then
        cat > $AVAHIFILE <<EOF
<?xml version="1.0" standalone='no'?>
<!DOCTYPE service-group SYSTEM "avahi-service.dtd">
<service-group>
  <name replace-wildcards="yes">Squid deb proxy on %h</name>
  <service protocol="ipv6">
    <type>_apt_proxy._tcp</type>
      <port>$PORT</port>
    </service>
  <service protocol="ipv4">
    <type>_apt_proxy._tcp</type>
      <port>$PORT</port>
    </service>
</service-group>
EOF
    fi
}

post_stop() {
    # stop advertising avahi service
    cat > "$AVAHIFILE" <<EOF
<?xml version="1.0" standalone='no'?>
<!DOCTYPE service-group SYSTEM "avahi-service.dtd">
<service-group>
</service-group>
EOF
}
