#!/bin/sh

curl -fsSL https://get.docker.com -o get-docker.sh
sh get-docker.sh
IP6BLOCK=`ip addr show | grep inet6 | grep -vE ' f[de][0-9a-f]{2}:' | grep /64 | head -n1 | sed -E "s/\s*inet6\s*(([0-9a-f]{1,4}:){3}[0-9a-f]{1,4}):.*\/64 scope global dynamic mngtmpaddr noprefixroute\s*/\1/"`
IP6SNAT_START="::2"
IP6SNAT_END=":ffff:ffff:ffff:ffff"
PRIVATE_V6="fd61:a12b:f6ed:f920::/64"
PRIVATE_V4="172.19.0.0/16"
SWITCHED_NETWORK=1
INTERFACE=`ip route | grep default | sed -E "s/.*dev ([^ ]+).*/\1/"`
IP6BLOCK_SIZE="64"
echo '{
  "experimental": true,
  "ip6tables": true,
  "log-driver": "json-file",
  "log-opts": {
    "max-size": "10m",
    "max-file": "10"
  }
}' > /etc/docker/daemon.json
systemctl restart docker
docker network create --ipv6 -o "com.docker.network.bridge.enable_ip_masquerade=false" --subnet $PRIVATE_V6 --subnet $PRIVATE_V4 ip6net
cat <<EOF >thing.py
import ipaddress
import subprocess
# CONFIG
# public range
subnet = "$IP6BLOCK::/64"
# private range to be snat'ted from
privateV6 = "fdbf:e8f7:b417:575a::/64"
# END CONFIG

def split_ipv6_subnet(subnet, chunks):
        # Convert the subnet to an IPv6 network object
        network = ipaddress.ip_network(subnet, strict=False)

        # Calculate the number of addresses in each chunk
        addresses_per_chunk = network.num_addresses // chunks

        # Ensure that we aren't left with an incomplete final chunk
        if network.num_addresses % chunks:
                addresses_per_chunk += 1

        results = []
        current_address = int(network.network_address)
        end_address = int(network.network_address) + network.num_addresses

        for i in range(chunks):
                # Start of the current chunk
                start = current_address

                # If this is the last chunk, set the end to the end address of the subnet
                if i == chunks - 1:
                        end = end_address
                else:
                        # Otherwise, set the end to the address at the end of the chunk
                        end = start + addresses_per_chunk

                # Convert the start and end addresses back to IPv6 addresses
                start_ip = ipaddress.IPv6Address(start)
                end_ip = ipaddress.IPv6Address(end - 1)  # Subtract 1 to get the last address in the chunk

                results.append(f"{start_ip}-{end_ip}")

                # Update the current address to the end of the chunk
                current_address = end

                # If we've reached the end of the subnet, break out of the loop
                if current_address >= end_address:
                        break

        return results


with open("/proc/sys/net/ipv4/ip_local_port_range", "r") as f:
        content = f.readline()
        PORT_RANGE_START, PORT_RANGE_END = map(int, content.split())

print(PORT_RANGE_START, PORT_RANGE_END)
PORT_RANGE_COUNT = PORT_RANGE_END - PORT_RANGE_START + 1
i = 0
for netRange in split_ipv6_subnet(subnet, PORT_RANGE_COUNT):
        print(str(PORT_RANGE_START + i), "->", netRange)
        subprocess.run(
                ["ip6tables", "-t", "nat", "-A", "POSTROUTING", "-p", "udp", "--sport", str(PORT_RANGE_START + i), "-s",
                 privateV6, "-j", "SNAT", "--to-source", netRange])
        subprocess.run(
                ["ip6tables", "-t", "nat", "-A", "POSTROUTING", "-p", "tcp", "--sport", str(PORT_RANGE_START + i), "-s",
                 privateV6, "-j", "SNAT", "--to-source", netRange])
        i += 1
EOF
python3 thing.py
DEBIAN_FRONTEND=noninteractive apt-get install iptables-persistent -y
iptables-save > /etc/iptables/rules.v4
ip6tables-save > /etc/iptables/rules.v6
if [ "$SWITCHED_NETWORK" -eq 1 ]; then
	echo Setting up ndppd to respond to ipv6 neighbour solicitations for the whole network
	echo "proxy $INTERFACE {
    router no
    rule $IP6BLOCK::/$IP6BLOCK_SIZE {
        static
    }
}" > /etc/ndppd.conf
	apt-get install ndppd
fi
seq 4 | xargs -n1 -P100 -I% docker run --pull always --detach --network ip6net -e PREFER_IPV6=1 --log-driver json-file --log-opt max-size=25m atdr.meo.ws/archiveteam/telegram-grab --concurrent 1 kiska1