#!/usr/bin/env python3
"""
Generate a config for an Adtran Total Access 900 series unit, plus the
matching TA5000 script that brings up gigabit port 2 on the customer's ONT and
builds its evc-map and up/down shapers (11500 kbps by default).

Two kinds of 900 are supported (pick with --type, or answer the first prompt):

    pri       PRI handoff to the customer's PBX on one of the T1 ports
    standard  lines delivered as SIP voice users on the 900's FXS ports

Run with no arguments to be prompted for everything:

    python "Ta900 pri ta5000.py"

Or pass any/all values as flags (anything left out is prompted for):

    python "Ta900 pri ta5000.py" --hostname ACME-TA908 --ip 10.68.4.18 \
        --gateway 10.68.4.17 --type pri --t1 3 --channels 12 --pilot 5735551234 \
        --customer "ACME Corp" --shelf 1 --slot 3 --port 2 --ont 14

    python "Ta900 pri ta5000.py" --type standard --numbers 5735551234,5735551235 ...

The TA900 config is written to <hostname>.cfg (use -o to change, -o - for
stdout) and the TA5000 script to <hostname>_ta5000.txt (use --ta5000-output to
change, - for stdout). Passwords are only ever asked for interactively so they don't end up
in shell history; press Enter at a password prompt to leave the template
placeholder in the output and fill it in by hand later.

Python 3.8+, standard library only.
"""

import argparse
import getpass
import ipaddress
import re
import sys
from pathlib import Path

T1_PORTS = (1, 2, 3, 4)                 # t1 0/1 - 0/4 on the TA900
MAX_B_CHANNELS = 23                     # timeslot 24 is always the D channel
DEFAULT_MASK = "255.255.255.240"        # from the template (/28)
EXPECTED_NET = ipaddress.ip_network("10.68.0.0/16")   # template uses 10.68.x.x
DEFAULT_SHAPER_KBPS = 11500             # TA5000 up/down shaper rate for port 2
MAX_FXS = 24                            # largest TA900 (TA924) has 24 FXS ports
FIRST_VOICE_USER = 1001                 # voice user for fxs 0/1; 0/2 is 1002, ...
DEFAULT_CID = "CID"                     # voice user description in the template

# --------------------------------------------------------------------------
# PRI handoff config template. [TOKENS] are filled in by render_pri().
# --------------------------------------------------------------------------
PRI_TEMPLATE = """hostname "[HOSTNAME]"
enable password [ENABLE_PASSWORD]
!
clock timezone -6-Central-Time
!
ip subnet-zero
ip classless
ip routing
!
!
ip name-server 216.106.1.11 216.106.1.12
!
!
no auto-config
!
event-history on
logging forwarding on
no logging console
logging forwarding receiver-ip 216.106.88.32
no logging email
!
no service password-encryption
!
username "root" password [ROOT_PASSWORD]
!
banner motd ~
THIS IS A PRIVATE COMPUTER SYSTEM.

This computer system including all related equipment, network devices
(specifically including Internet access), are provided only for
authorized use. All computer systems may be monitored for all lawful
purposes, including to ensure that their use is authorized, for
management of the system, to facilitate protection against unauthorized
access, and to verify security procedures, survivability and
operational security. Monitoring includes active attacks by authorized
personnel and their entities to test or verify the security of the
system. During monitoring, information may be examined, recorded,
copied and used for authorized purposes. All information including
personal information, placed on or sent over this system may be
monitored. Uses of this system, authorized or unauthorized, constitutes
consent to monitoring of this system. Unauthorized use may subject you
to criminal prosecution. Evidence of any such unauthorized use
collected during monitoring may be used for administrative, criminal or
other adverse action. Use of this system constitutes consent to
monitoring for these purposes.
~
!
!
no ip firewall alg msn
no ip firewall alg h323
!
no dot11ap access-point-control
!
!
!
!
!
!
!
!
!
!
!
!
interface eth 0/1
  ip address [IP_ADDRESS] [SUBNET_MASK]
  no shutdown
  media-gateway ip primary
!
!
!
!
[T1_INTERFACES]
!
!
!
!
interface pri 1
  isdn name-delivery setup
  connect t1 0/[T1_PORT] tdm-group 1
  no shutdown
!
!
!
isdn-group 1
  connect pri 1
!
!
!
!
ip access-list standard RemoteAdmin
  permit 216.106.0.0 0.0.63.255
  permit 216.106.64.0 0.0.31.255
  permit 64.85.192.0 0.0.31.255
  permit 174.34.0.0 0.0.31.255
  permit 174.34.32.0 0.0.15.255
  permit 199.187.160.0 0.0.3.255
  permit 172.16.0.0 0.0.31.255
  permit 10.0.0.0 0.255.255.255
  permit 192.168.0.0 0.0.255.255
!
ip access-list standard SecureAdmin
  permit 216.106.88.0 0.0.0.255
  permit 216.106.0.128 0.0.0.63
  permit 216.106.44.0 0.0.0.255
  permit 172.16.0.0 0.0.31.255
  permit 174.34.30.160 0.0.0.15
  permit 10.0.0.0 0.255.255.255
  permit 192.168.0.0 0.0.255.255
!
ip access-list extended Momentum
  permit ip host 208.85.131.28  any     log
  permit ip host 98.167.82.12  any     log
  permit ip 4.16.120.48 0.0.0.15  any     log
  permit ip 4.78.147.128 0.0.0.31  any     log
  permit ip 8.20.86.0 0.0.0.255  any     log
  permit ip host 40.139.172.22  any     log
  permit ip host 40.139.173.102  any     log
  permit ip 63.209.193.0 0.0.0.255  any     log
  permit ip 63.214.22.128 0.0.0.31  any     log
  permit ip 65.246.4.248 0.0.0.7  any     log
  permit ip 96.90.37.88 0.0.0.7  any     log
  permit ip 162.244.96.0 0.0.0.255  any     log
  permit ip 162.244.97.0 0.0.0.255  any     log
  permit ip 204.16.52.0 0.0.0.255  any     log
  permit ip 204.16.54.0 0.0.0.255  any     log
  permit ip 204.16.55.0 0.0.0.255  any     log
  permit ip 208.67.12.0 0.0.0.255  any     log
  permit ip 208.67.14.0 0.0.0.63  any     log
  permit ip 208.67.15.0 0.0.0.255  any     log
  permit ip 208.85.134.0 0.0.0.255  any     log
  permit ip 209.55.5.108 0.0.0.3  any     log
  permit ip 209.55.25.32 0.0.0.31  any     log
  permit ip host 209.55.28.12  any     log
  permit ip host 209.55.25.4  any     log
  permit ip host 209.244.0.3  any     log
  permit ip host 209.244.0.4  any     log
  permit ip host 209.55.18.115  any     log
  permit ip 216.106.53.12 0.0.0.3  any     log
!
!
ip route 0.0.0.0 0.0.0.0 [GATEWAY]
!
!
ip ssh-server 2601
no ip tftp server
no ip tftp server overwrite
ip http authentication default
no ip http server
no ip http secure-server
no snmp agent
no ip ftp server
no ip scp server
no ip sntp server
!
!
!
snmp-server enable traps
snmp-server community socket RO
snmp-server community S0ck3t RO
!
!
!
ip http access-class RemoteAdmin in
!
!
!
!
!
!
!
voice feature-mode network
voice forward-mode network
!
!
!
!
!
!
voice dial-plan 1 always-permitted N11
voice dial-plan 2 operator-assisted 0$
voice dial-plan 5 international 0-11-$
voice dial-plan 6 specify-carrier 1-01-XXXX-$
voice dial-plan 7 toll-free [01]-8[087654][087654]-NXX-XXXX
voice dial-plan 8 toll-free 8[087654][087654]-NXX-XXXX
voice dial-plan 9 900-number [01]-900-NXX-XXXX
voice dial-plan 10 900-number 900-NXX-XXXX
voice dial-plan 11 900-number [01]-976-XXX$
voice dial-plan 12 900-number 976-XXX$
voice dial-plan 13 long-distance [01]-NXX-NXX-XXXX
voice dial-plan 14 local NXX-NXX-XXXX
voice dial-plan 15 extensions XX$
!
!
!
!
voice codec-list FAX
  codec g711ulaw
!
!
!
!
voice trunk T01 type sip
  match ani "$" substitute "[PILOT_NUMBER]"
  match ani "$" add p-asserted-identity "$"
  caller-id-override emergency-outbound match-substitute
  sip-server primary mymtm.us
  registrar primary mymtm.us
  registrar threshold absolute 280
  registrar expire-time 300
  sip-header-passthrough both
  outbound-proxy primary pbx.west.mymtm.us
  domain "mymtm.us"
  register [PILOT_NUMBER] auth-name "[PILOT_NUMBER]" password "[SIP_PASSWORD]"
  grammar request-uri host domain
  grammar from host domain
  grammar p-asserted-identity host domain
  grammar to host domain
  !
voice trunk T51 type isdn
  description "to PBX"
  resource-selection linear ascending
  connect isdn-group 1
  modem-passthrough detection-time 15
  rtp delay-mode adaptive
!
!
voice grouped-trunk PRI
  description "PRI"
  trunk T51
  accept $ cost 1
!
!
voice grouped-trunk PRIOUTBOUND
  description "PRIoutbound"
  trunk T01
  accept $ cost 0
!
!
!
!
!
!
!
!
ip sip
!
!
!
!
!
!
!
!
line con 0
  login local-userlist
!
line telnet 0 4
  login local-userlist
  no shutdown
  ip access-class RemoteAdmin in
line ssh 0 4
  login local-userlist
  no shutdown
!
sntp server ntp.socket.net
!
end
"""

# --------------------------------------------------------------------------
# Standard 900 config, from Standard_Adtran_900_Config.txt: every T1 shut down,
# lines delivered as SIP voice users on FXS ports. [SIP_REGISTRATIONS] and
# [VOICE_USERS] get one entry per line.
# --------------------------------------------------------------------------
STANDARD_TEMPLATE = """hostname "[HOSTNAME]"
enable password [ENABLE_PASSWORD]
!
clock timezone -6-Central-Time
!
ip subnet-zero
ip classless
ip routing
!
!
ip name-server 216.106.1.11 216.106.1.12
!
!
no auto-config
!
event-history on
logging forwarding on
no logging console
logging forwarding receiver-ip 216.106.88.32
no logging email
!
service password-encryption
!
username "root" password [ROOT_PASSWORD]
!
banner motd ~
THIS IS A PRIVATE COMPUTER SYSTEM.

This computer system including all related equipment, network devices
(specifically including Internet access), are provided only for
authorized use. All computer systems may be monitored for all lawful
purposes, including to ensure that their use is authorized, for
management of the system, to facilitate protection against unauthorized
access, and to verify security procedures, survivability and
operational security. Monitoring includes active attacks by authorized
personnel and their entities to test or verify the security of the
system. During monitoring, information may be examined, recorded,
copied and used for authorized purposes. All information including
personal information, placed on or sent over this system may be
monitored. Uses of this system, authorized or unauthorized, constitutes
consent to monitoring of this system. Unauthorized use may subject you
to criminal prosecution. Evidence of any such unauthorized use
collected during monitoring may be used for administrative, criminal or
other adverse action. Use of this system constitutes consent to
monitoring for these purposes.
~
!
!
no ip firewall alg msn
no ip firewall alg h323
!
no dot11ap access-point-control
!
!
!
!
!
!
!
!
!
!
!
!
interface eth 0/1
  ip address [IP_ADDRESS] [SUBNET_MASK]
  no shutdown
  media-gateway ip primary
!
!
!
!
interface t1 0/1
  shutdown
!
interface t1 0/2
  shutdown
!
interface t1 0/3
  shutdown
!
interface t1 0/4
  shutdown
!
!
!
!
!
!
!
!
!
ip access-list standard RemoteAdmin
  permit 216.106.0.0 0.0.63.255
  permit 216.106.64.0 0.0.31.255
  permit 64.85.192.0 0.0.31.255
  permit 174.34.0.0 0.0.31.255
  permit 174.34.32.0 0.0.15.255
  permit 199.187.160.0 0.0.3.255
  permit 172.16.0.0 0.0.31.255
  permit 10.0.0.0 0.255.255.255
  permit 192.168.0.0 0.0.255.255
!
ip access-list standard SecureAdmin
  permit 216.106.88.0 0.0.0.255
  permit 216.106.0.128 0.0.0.63
  permit 216.106.44.0 0.0.0.255
  permit 172.16.0.0 0.0.31.255
  permit 174.34.30.160 0.0.0.15
  permit 10.0.0.0 0.255.255.255
  permit 192.168.0.0 0.0.255.255
!
ip access-list extended Momentum
  permit ip host 208.85.131.28  any     log
  permit ip host 98.167.82.12  any     log
  permit ip 4.16.120.48 0.0.0.15  any     log
  permit ip 4.78.147.128 0.0.0.31  any     log
  permit ip 8.20.86.0 0.0.0.255  any     log
  permit ip host 40.139.172.22  any     log
  permit ip host 40.139.173.102  any     log
  permit ip 63.209.193.0 0.0.0.255  any     log
  permit ip 63.214.22.128 0.0.0.31  any     log
  permit ip 65.246.4.248 0.0.0.7  any     log
  permit ip 96.90.37.88 0.0.0.7  any     log
  permit ip 162.244.96.0 0.0.0.255  any     log
  permit ip 162.244.97.0 0.0.0.255  any     log
  permit ip 204.16.52.0 0.0.0.255  any     log
  permit ip 204.16.54.0 0.0.0.255  any     log
  permit ip 204.16.55.0 0.0.0.255  any     log
  permit ip 208.67.12.0 0.0.0.255  any     log
  permit ip 208.67.14.0 0.0.0.63  any     log
  permit ip 208.67.15.0 0.0.0.255  any     log
  permit ip 208.85.134.0 0.0.0.255  any     log
  permit ip 209.55.5.108 0.0.0.3  any     log
  permit ip 209.55.25.32 0.0.0.31  any     log
  permit ip host 209.55.28.12  any     log
  permit ip host 209.55.25.4  any     log
  permit ip host 209.244.0.3  any     log
  permit ip host 209.244.0.4  any     log
  permit ip host 209.55.18.115  any     log
  permit ip 216.106.53.12 0.0.0.3  any     log
!
!
ip route 0.0.0.0 0.0.0.0 [GATEWAY]
!
!
ip ssh-server 2601
no ip tftp server
no ip tftp server overwrite
ip http authentication default
no ip http server
no ip http secure-server
no snmp agent
no ip ftp server
no ip scp server
no ip sntp server
!
!
!
snmp-server enable traps
snmp-server community socket RO
snmp-server community S0ck3t RO
!
!
!
ip http access-class RemoteAdmin in
!
!
!
!
!
!
!
voice feature-mode network
voice forward-mode network
!
!
!
!
!
!
voice dial-plan 1 always-permitted N11
voice dial-plan 2 operator-assisted 0$
voice dial-plan 5 international 0-11-$
voice dial-plan 6 specify-carrier 1-01-XXXX-$
voice dial-plan 7 toll-free [01]-8[087654][087654]-NXX-XXXX
voice dial-plan 8 toll-free 8[087654][087654]-NXX-XXXX
voice dial-plan 9 900-number [01]-900-NXX-XXXX
voice dial-plan 10 900-number 900-NXX-XXXX
voice dial-plan 11 900-number [01]-976-XXX$
voice dial-plan 12 900-number 976-XXX$
voice dial-plan 13 long-distance [01]-NXX-NXX-XXXX
voice dial-plan 14 local NXX-NXX-XXXX
voice dial-plan 15 extensions XX$
!
!
!
!
voice codec-list FAX
  codec g711ulaw
!
!
!
voice trunk T01 type sip
  sip-server primary mymtm.us
  registrar primary mymtm.us
  outbound-proxy primary pbx.west.mymtm.us
  domain "mymtm.us"
[SIP_REGISTRATIONS]
  grammar request-uri host domain
  grammar from host domain
  default-ring-cadence internal
!
!
voice grouped-trunk CPESIPTG
  description "Dial Patterns to SIP TG"
  trunk T01
  accept $ cost 0
!
!
[VOICE_USERS]
!
!
!
!
!
!
ip sip
!
!
!
!
!
!
!
!
line con 0
  login local-userlist
!
line telnet 0 4
  login local-userlist
  no shutdown
  ip access-class RemoteAdmin in
line ssh 0 4
  login local-userlist
  no shutdown
!
sntp server ntp.socket.net
!
end
"""

# --------------------------------------------------------------------------
# TA5000 script, from Adtran_900_Ta5000_template.txt. Enables gigabit port 2
# on the ONT and hands it to the TA900 via a static-IP evc-map.
# --------------------------------------------------------------------------
TA5000_TEMPLATE = """interface gigabit-ethernet [ONT_ID]/0/2@[SHELF]/[SLOT]/[PORT].gpon
speed auto
description "ETH: [CUSTOMER_NAME] 900 2"
mac limit 2
no shutdown
exit

shaper "DATA_[PORT]_[ONT_ID]b_DOWN" 1/1
per remote-device [ONT_ID]@[SHELF]/[SLOT]/[PORT].gpon queue 1
rate [SHAPER_RATE]
no shut
exit

evc-map "DATA_[PORT]_[ONT_ID]b" [SHELF]/[SLOT]
connect evc "MMTM-STATIC"
connect uni gigabit-ethernet [ONT_ID]/0/2@[SHELF]/[SLOT]/[PORT].gpon
subscriber access static-ip 10.68.[REST_OF_IP] 00:00:00:00:00:00 [GATEWAY] 00:00:00:00:00:00
connect gpon upstream channel 2
connect qos downstream map-profile "Port2"
men-pri 0
men-c-tag-pri 0
subscriber access dhcpv6 mode block
subscriber access dhcpv6 relay-agent mode disable
description "[CUSTOMER_NAME] 900"
no shutdown
exit

shaper "DATA_[PORT]_[ONT_ID]b_UP" [ONT_ID]@[SHELF]/[SLOT]/[PORT]
per interface gpon [ONT_ID]/0/1@[SHELF]/[SLOT]/[PORT].gpon channel 2
rate [SHAPER_RATE]
no shut
exit
"""

# What a password placeholder looks like in the output if it's left unfilled.
UNFILLED = {
    "ENABLE_PASSWORD": "[ENABLE_PASSWORD]",
    "ROOT_PASSWORD": "[PASSWORD]",
    "SIP_PASSWORD": "[PASSWORD]",
    "LINE_PASSWORD": "[16characterpassword]",   # standard 900, per line
}


# --------------------------------------------------------------------------
# Input parsing / validation. Each parser returns the cleaned value or raises
# ValueError with a message meant for the person typing.
# --------------------------------------------------------------------------
def parse_hostname(text):
    if not re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9._-]{0,62}", text):
        raise ValueError("Hostname must be 1-63 characters: letters, digits, '.', '_' or '-'.")
    return text


def parse_t1_port(text):
    text = text.strip().lower().replace("t1", "").strip()
    if text.startswith("0/"):           # accept "3", "0/3" or "t1 0/3"
        text = text[2:]
    if not text.isdigit() or int(text) not in T1_PORTS:
        raise ValueError(f"T1 port must be one of {', '.join(f'0/{p}' for p in T1_PORTS)}.")
    return int(text)


def parse_channels(text):
    if not text.isdigit() or not 1 <= int(text) <= MAX_B_CHANNELS:
        raise ValueError(f"Channel count must be a number from 1 to {MAX_B_CHANNELS}.")
    return int(text)


def parse_type(text):
    text = text.strip().lower()
    if text in ("1", "pri"):
        return "pri"
    if text in ("2", "standard", "std", "fxs"):
        return "standard"
    raise ValueError("Enter 1 (PRI handoff) or 2 (standard / FXS voice users).")


def parse_phone(text):
    digits = re.sub(r"[\s().+-]", "", text)
    if len(digits) == 11 and digits.startswith("1"):
        digits = digits[1:]
    if not digits.isdigit() or len(digits) != 10:
        raise ValueError("Phone number must be a 10-digit number, e.g. 5735551234.")
    return digits


def parse_description(text):
    text = text.strip()
    if not text:
        raise ValueError("Description can't be blank.")
    if re.search(r'["?]', text):
        raise ValueError("Description can't contain double quotes or '?'.")
    return text


def parse_list(text, parse_item):
    """Comma-separated values for flags like --numbers."""
    return [parse_item(item) for item in text.split(",")]


def parse_mask(text):
    """Accepts 255.255.255.240, /28 or 28. Returns the dotted mask."""
    try:
        return str(ipaddress.ip_network(f"0.0.0.0/{text.strip().lstrip('/')}").netmask)
    except ValueError:
        raise ValueError(f"'{text}' is not a valid subnet mask or prefix length.") from None


def parse_ip(text, mask):
    """Accepts 10.68.4.18 or 10.68.4.18/28. Returns an IPv4Interface."""
    if "/" in text:
        text, _, prefix = text.partition("/")
        mask = parse_mask(prefix)
    try:
        iface = ipaddress.IPv4Interface(f"{text.strip()}/{mask}")
    except ValueError:
        raise ValueError(f"'{text}' is not a valid IPv4 address.") from None
    net = iface.network
    if net.prefixlen < 31 and iface.ip in (net.network_address, net.broadcast_address):
        raise ValueError(f"{iface.ip} is the network or broadcast address of {net}; pick a host address.")
    return iface


def parse_gateway(text, iface):
    try:
        gw = ipaddress.IPv4Address(text.strip())
    except ValueError:
        raise ValueError(f"'{text}' is not a valid IPv4 address.") from None
    net = iface.network
    if gw not in net:
        raise ValueError(f"Gateway {gw} is not in the unit's subnet ({net}).")
    if gw == iface.ip:
        raise ValueError("Gateway can't be the same address as the unit.")
    if net.prefixlen < 31 and gw in (net.network_address, net.broadcast_address):
        raise ValueError(f"{gw} is the network or broadcast address of {net}.")
    return gw


def parse_customer(text):
    text = text.strip()
    if not text:
        raise ValueError("Customer name can't be blank.")
    if re.search(r'["?]', text):
        # It goes inside a quoted description; '?' triggers CLI inline help.
        raise ValueError("Customer name can't contain double quotes or '?'.")
    return text


def positive_int(label, maximum=None):
    """Build a parser for a whole number from 1 to maximum (no upper limit if None)."""
    def parse(text):
        if not text.strip().isdigit() or int(text) < 1 or (maximum and int(text) > maximum):
            limit = f" from 1 to {maximum}" if maximum else " of 1 or more"
            raise ValueError(f"{label} must be a whole number{limit}.")
        return int(text)
    return parse


def parse_rest_of_ip(text):
    """The last two octets of the 10.68.x.x static IP, e.g. '4.18'."""
    text = text.strip()
    if text.startswith("10.68."):       # accept the full address too
        text = text[len("10.68."):]
    octets = text.split(".")
    if len(octets) != 2 or not all(o.isdigit() and int(o) <= 255 for o in octets):
        raise ValueError("Enter the last two octets of the 10.68.x.x address, e.g. 4.18.")
    return ".".join(str(int(o)) for o in octets)


def resolve(value, prompt, parse, default=None):
    """Use the command-line value if given, otherwise keep asking until valid.
    With a default, pressing Enter at the prompt accepts it."""
    if value is not None:
        try:
            return parse(value)
        except ValueError as err:
            sys.exit(f"error: {err}")
    if default is not None:
        prompt = f"{prompt} [{default}]"
    while True:
        try:
            text = input(f"{prompt}: ").strip()
            return parse(default if not text and default is not None else text)
        except ValueError as err:
            print(f"  {err}")
        except EOFError:
            sys.exit(f"\nerror: no value given for: {prompt}")


def ask_secret(label):
    """Prompt without echo. Returns None if left blank."""
    while True:
        try:
            value = getpass.getpass(f"{label} (Enter to leave placeholder): ")
        except EOFError:
            return None
        if not value:
            return None
        if re.search(r'[\s"?]', value):
            # '?' triggers inline help if the config is pasted into the AOS CLI.
            print("  Can't contain spaces, double quotes or '?'.")
            continue
        return value


# --------------------------------------------------------------------------
# Config rendering
# --------------------------------------------------------------------------
def timeslots(channels):
    """B channels 1..N plus the D channel on 24."""
    if channels == MAX_B_CHANNELS:
        return "1-24"
    if channels == 1:
        return "1,24"
    return f"1-{channels},24"


def t1_interfaces(port, channels):
    """The chosen T1 carries the PRI; every other T1 is shut down."""
    lines = []
    for p in T1_PORTS:
        lines.append(f"interface t1 0/{p}")
        if p == port:
            lines.append(f"  description T1 0/{p} to PBX")
            lines.append(f"  tdm-group 1 timeslots {timeslots(channels)} speed 64")
            lines.append("  no shutdown")
        else:
            lines.append("  shutdown")
        lines.append("!")
    return "\n".join(lines)


def render_pri(hostname, iface, gateway, t1_port, channels, pilot,
               enable_password=None, root_password=None, sip_password=None):
    values = {
        "HOSTNAME": hostname,
        "IP_ADDRESS": str(iface.ip),
        "SUBNET_MASK": str(iface.netmask),
        "GATEWAY": str(gateway),
        "T1_INTERFACES": t1_interfaces(t1_port, channels),
        "T1_PORT": str(t1_port),
        "PILOT_NUMBER": pilot,
        "ENABLE_PASSWORD": enable_password or UNFILLED["ENABLE_PASSWORD"],
        "ROOT_PASSWORD": root_password or UNFILLED["ROOT_PASSWORD"],
        "SIP_PASSWORD": sip_password or UNFILLED["SIP_PASSWORD"],
    }
    return fill(PRI_TEMPLATE, values)


def render_standard(hostname, iface, gateway, lines,
                    enable_password=None, root_password=None):
    """lines: one (phone_number, description, sip_password or None) per FXS
    port, in port order starting at fxs 0/1."""
    registrations, users = [], []
    for n, (number, description, password) in enumerate(lines, start=1):
        password = password or UNFILLED["LINE_PASSWORD"]
        registrations.append(f'  register {number} auth-name "{number}" password {password}')
        users += [
            f"voice user {FIRST_VOICE_USER + n - 1}",
            f"  connect fxs 0/{n}",
            "  password 1234",
            f'  description "{description}"',
            f"  sip-identity {number} T01",
            f"  sip-authentication password {password}",
            "!",
            "!",
        ]
    values = {
        "HOSTNAME": hostname,
        "IP_ADDRESS": str(iface.ip),
        "SUBNET_MASK": str(iface.netmask),
        "GATEWAY": str(gateway),
        "SIP_REGISTRATIONS": "\n".join(registrations),
        "VOICE_USERS": "\n".join(users),
        "ENABLE_PASSWORD": enable_password or UNFILLED["ENABLE_PASSWORD"],
        "ROOT_PASSWORD": root_password or UNFILLED["ROOT_PASSWORD"],
    }
    return fill(STANDARD_TEMPLATE, values)


def render_ta5000(customer, shelf, slot, port, ont_id, rest_of_ip, gateway, rate):
    values = {
        "CUSTOMER_NAME": customer,
        "SHELF": str(shelf),
        "SLOT": str(slot),
        "PORT": str(port),
        "ONT_ID": str(ont_id),
        "REST_OF_IP": rest_of_ip,
        "GATEWAY": str(gateway),
        "SHAPER_RATE": str(rate),
    }
    return fill(TA5000_TEMPLATE, values)


def fill(template, values):
    # Single pass so a value can never be mistaken for another token.
    return re.sub(
        r"\[(" + "|".join(values) + r")\]",
        lambda m: values[m.group(1)],
        template,
    )


def write(text, out):
    if out == "-":
        sys.stdout.write(text)
    else:
        with open(Path(out), "w", encoding="utf-8", newline="\n") as fh:
            fh.write(text)


# --------------------------------------------------------------------------
def main():
    ap = argparse.ArgumentParser(
        description="Generate an Adtran TA900 config (PRI handoff or standard FXS)"
                    " and its TA5000 ONT port 2 script.",
        epilog="Any value not given as a flag is prompted for.",
    )
    ap.add_argument("--type", help="'pri' (PRI handoff) or 'standard' (FXS voice users)")
    ap.add_argument("--hostname", help="unit hostname (asset tag)")
    ap.add_argument("--ip", help="eth 0/1 address, e.g. 10.68.4.18 (or 10.68.4.18/28)")
    ap.add_argument("--mask",
                    help=f"subnet mask or prefix length (default {DEFAULT_MASK})")
    ap.add_argument("--gateway", help="default gateway")
    ap.add_argument("--t1", help="PRI: T1 port for the PRI handoff: 1-4 (t1 0/1 - 0/4)")
    ap.add_argument("--channels", help=f"PRI: number of B channels, 1-{MAX_B_CHANNELS}")
    ap.add_argument("--pilot", help="PRI: 10-digit pilot number")
    ap.add_argument("--lines", help=f"standard: number of lines / FXS ports, 1-{MAX_FXS}")
    ap.add_argument("--numbers",
                    help="standard: comma-separated phone numbers, in FXS port order")
    ap.add_argument("--descriptions",
                    help=f"standard: comma-separated voice user descriptions"
                         f" (default '{DEFAULT_CID}')")
    ap.add_argument("--skip-passwords", action="store_true",
                    help="don't prompt for passwords; leave placeholders in the output")
    ap.add_argument("--customer", help="customer name for the TA5000 port description")
    ap.add_argument("--shelf", help="TA5000 shelf")
    ap.add_argument("--slot", help="TA5000 slot of the GPON card")
    ap.add_argument("--port", help="GPON port on that card")
    ap.add_argument("--ont", help="ONT ID on that GPON port")
    ap.add_argument("--rest-of-ip",
                    help="last two octets of the evc-map static IP 10.68.x.x, e.g. 4.18"
                         " (default: from the TA900 IP)")
    ap.add_argument("--rate",
                    help=f"up/down shaper rate in kbps (default {DEFAULT_SHAPER_KBPS})")
    ap.add_argument("-o", "--output",
                    help="TA900 config file (default <hostname>.cfg, '-' for stdout)")
    ap.add_argument("--ta5000-output",
                    help="TA5000 script file (default <hostname>_ta5000.txt, '-' for stdout)")
    args = ap.parse_args()

    if args.type is None:
        print("Type of 900:\n  1) PRI handoff\n  2) Standard (FXS voice users)")
    kind = resolve(args.type, "Choose 1 or 2", parse_type)
    if kind == "pri" and (args.lines or args.numbers or args.descriptions):
        sys.exit("error: --lines/--numbers/--descriptions are for --type standard.")
    if kind == "standard" and (args.t1 or args.channels or args.pilot):
        sys.exit("error: --t1/--channels/--pilot are for --type pri.")

    hostname = resolve(args.hostname, "Hostname (asset tag)", parse_hostname)
    mask = resolve(args.mask, "Subnet mask", parse_mask, default=DEFAULT_MASK)
    iface = resolve(args.ip, "TA900 IP address", lambda t: parse_ip(t, mask))
    gateway = resolve(args.gateway, "Gateway", lambda t: parse_gateway(t, iface))

    if kind == "pri":
        t1_port = resolve(args.t1, "T1 port for the PRI (1-4)", parse_t1_port)
        channels = resolve(args.channels, f"Number of channels (1-{MAX_B_CHANNELS})",
                           parse_channels)
        pilot = resolve(args.pilot, "Pilot number", parse_phone)
    else:
        numbers = resolve(args.numbers, "", lambda t: parse_list(t, parse_phone)) \
            if args.numbers else None
        count = len(numbers) if numbers else \
            resolve(args.lines, f"Number of lines / FXS ports (1-{MAX_FXS})",
                    positive_int("Number of lines", MAX_FXS))
        if count > MAX_FXS:
            sys.exit(f"error: at most {MAX_FXS} lines.")
        descriptions = resolve(args.descriptions, "", lambda t: parse_list(t, parse_description)) \
            if args.descriptions else None
        if descriptions and len(descriptions) != count:
            sys.exit(f"error: --descriptions has {len(descriptions)} entries but there are"
                     f" {count} lines.")
        if numbers is None or descriptions is None:
            new_numbers, new_descriptions = [], []
            for n in range(1, count + 1):
                user = f"Line {n} (fxs 0/{n}, voice user {FIRST_VOICE_USER + n - 1})"
                new_numbers.append(numbers[n - 1] if numbers else
                                   resolve(None, f"{user} phone number", parse_phone))
                new_descriptions.append(descriptions[n - 1] if descriptions else
                                        resolve(None, f"{user} description", parse_description,
                                                default=DEFAULT_CID))
            numbers, descriptions = new_numbers, new_descriptions
        dupes = sorted({x for x in numbers if numbers.count(x) > 1})
        if dupes:
            sys.exit(f"error: phone number used on more than one line: {', '.join(dupes)}")

    customer = resolve(args.customer, "Customer name", parse_customer)
    shelf = resolve(args.shelf, "TA5000 shelf", positive_int("Shelf"))
    slot = resolve(args.slot, "TA5000 slot", positive_int("Slot"))
    port = resolve(args.port, "GPON port", positive_int("GPON port"))
    ont_id = resolve(args.ont, "ONT ID", positive_int("ONT ID"))
    suggested = ".".join(str(iface.ip).split(".")[2:]) if iface.ip in EXPECTED_NET else None
    rest_of_ip = resolve(args.rest_of_ip, "evc-map static IP 10.68.x.x, last two octets", parse_rest_of_ip,
                         default=suggested)
    rate = resolve(args.rate, "Shaper rate (kbps)", positive_int("Shaper rate"),
                   default=str(DEFAULT_SHAPER_KBPS))

    enable_pw = root_pw = sip_pw = None
    line_pws = []
    if not args.skip_passwords:
        enable_pw = ask_secret("Enable password")
        root_pw = ask_secret("'root' user password")
        if kind == "pri":
            sip_pw = ask_secret(f"SIP registration password for {pilot}")
        else:
            line_pws = [ask_secret(f"SIP password for {number} (fxs 0/{n})")
                        for n, number in enumerate(numbers, start=1)]
    if kind == "standard":
        line_pws += [None] * (len(numbers) - len(line_pws))

    if kind == "pri":
        config = render_pri(hostname, iface, gateway, t1_port, channels, pilot,
                            enable_pw, root_pw, sip_pw)
    else:
        config = render_standard(hostname, iface, gateway,
                                 list(zip(numbers, descriptions, line_pws)),
                                 enable_pw, root_pw)

    ta5000 = render_ta5000(customer, shelf, slot, port, ont_id, rest_of_ip, gateway, rate)

    out = args.output or f"{hostname}.cfg"
    ta5000_out = args.ta5000_output or f"{hostname}_ta5000.txt"
    # Keep stdout clean when piping.
    info = sys.stderr if "-" in (out, ta5000_out) else sys.stdout

    write(config, out)
    if out == "-" and ta5000_out == "-":
        sys.stdout.write("\n")
    write(ta5000, ta5000_out)

    print(file=info)
    print(f"  Hostname : {hostname}", file=info)
    print(f"  Address  : {iface.ip} {iface.netmask}  (gateway {gateway})", file=info)
    if kind == "pri":
        print(f"  PRI      : t1 0/{t1_port}, {channels} channel{'s' if channels != 1 else ''}"
              f" (timeslots {timeslots(channels)})", file=info)
        print(f"  Pilot    : {pilot}", file=info)
    else:
        print(f"  Standard : {len(numbers)} line{'s' if len(numbers) != 1 else ''}", file=info)
        for n, (number, description) in enumerate(zip(numbers, descriptions), start=1):
            print(f"             fxs 0/{n}  voice user {FIRST_VOICE_USER + n - 1}"
                  f"  {number}  \"{description}\"", file=info)
    print(f"  TA5000   : ONT {ont_id}/0/2@{shelf}/{slot}/{port}.gpon, \"{customer}\","
          f" static IP 10.68.{rest_of_ip}, shapers {rate} kbps", file=info)
    for label, path in (("TA900", out), ("TA5000", ta5000_out)):
        if path != "-":
            print(f"  Written  : {path}  ({label})", file=info)

    if iface.ip not in EXPECTED_NET:
        print(f"\n  Note: {iface.ip} is outside {EXPECTED_NET}, which the template normally uses.",
              file=info)
    passwords = [("enable password", enable_pw), ("root password", root_pw)]
    if kind == "pri":
        passwords.append(("SIP registration password", sip_pw))
    else:
        passwords += [(f"SIP password for {number}", pw) for number, pw in zip(numbers, line_pws)]
        short = [number for number, pw in zip(numbers, line_pws) if pw and len(pw) != 16]
        if short:
            print(f"\n  Note: SIP password for {', '.join(short)} isn't 16 characters.", file=info)
    missing = [name for name, pw in passwords if not pw]
    if missing:
        print(f"\n  Still to fill in by hand: {', '.join(missing)}.", file=info)


if __name__ == "__main__":
    try:
        main()
    except KeyboardInterrupt:
        sys.exit("\nCancelled.")
