import socket
import struct


def synproxy_build_message(mode, ipaddr, port, proto, tcpmss, tcpsack, tcpwscale):
    """
    Build and return synchronization message

    Message structure:
      - 32 bits: IPv4 address
      - 16 bits: Port number
      - 8  bits: Protocol
      - 8  bits: Flags
      - 16 bits: TCP MSS value
      - 8  bits: TCP SACK value [0,1]
      - 8  bits: TCP window scaling value [0-14]
    """
    # Build flags
    flags = 0
    if mode == 'flush':
        flags |= 0b0000001
        tcpmss = 0
        tcpsack = 0
        tcpwscale = 0
        port = 0
        proto = 0
    elif mode == 'add':
        flags |= 0b0000010
    elif mode == 'mod':
        flags |= 0b0000100
    elif mode == 'del':
        flags |= 0b0001000
        tcpmss = 0
        tcpsack = 0
        tcpwscale = 0
    # Pack message
    msg = socket.inet_pton(socket.AF_INET, ipaddr) + struct.pack('!HBBHBB', port, proto, flags, tcpmss, tcpsack, tcpwscale)
    # Return built message
    return msg