#!/usr/bin/env python

import argparse
from io import StringIO
import subprocess
import urllib.parse


def main():
    parser = argparse.ArgumentParser(
        description="""
            Fetch the wifi password and generate a QR code.

            This program assumes that the network PSK is stored
            in the password-store, and will look for it
            at the path `wifi/<essid>`.
        """,
    )
    parser.add_argument(
        "-H",
        "--hidden",
        action="store_true",
        help="Indicate that this network's SSID is hidden.",
    )
    parser.add_argument("essid", help="ESSID for this network")

    args = parser.parse_args()

    psk = subprocess.check_output(["pass", f"wifi/{args.essid}"], text=True).strip()

    hidden_data = "H:true;" if args.hidden else ""
    qr_data = f"WIFI:T:WPA;S:{quote(args.essid)};{hidden_data}P:{quote(psk)};;"

    proc = subprocess.Popen(["qrencode", "-tANSI"], stdin=subprocess.PIPE, text=True)
    proc.communicate(qr_data)


PRINTABLE = [*range(0x20, 0x3B), *range(0x3C, 0x7F)]


def quote(s: str) -> str:
    return urllib.parse.quote(s, safe=PRINTABLE)


if __name__ == "__main__":
    main()
