#!/usr/bin/env python
# -*- coding: utf-8 -*-

import os
import sys
import time
import subprocess

CONFFILE = "/var/openfw/tailscale/settings"
TS_BIN   = "/usr/bin/tailscale"
TSD_BIN  = "/usr/sbin/tailscaled"
INIT_SCRIPT = "/etc/init.d/tailscaled"

def print_help():
    """Displays command line usage help."""
    print "Tailscale Wrapper Helper"
    print "Usage: %s [OPTION]" % sys.argv[0]
    print ""
    print "Options:"
    print "  --start        Starts the tailscaled daemon and brings up the connection."
    print "  --stop         Brings down the interface and stops tailscaled."
    print "  --restart      Stops and then starts the Tailscale service."
    print "  --status       Displays current Tailscale status."
    print "  -h, --help     Displays this help message."
    print ""

def read_config(filepath):
    config = {}
    if not os.path.exists(filepath):
        return config
    
    with open(filepath, "r") as f:
        for line in f:
            line = line.strip()
            if not line or line.startswith("#"):
                continue
            if "=" in line:
                key, val = line.split("=", 1)
                config[key.strip()] = val.strip()
    return config

def stop_service():
    devnull = open(os.devnull, 'w')
    subprocess.call([TS_BIN, "down"], stdout=devnull, stderr=devnull)
    
    if os.path.exists(INIT_SCRIPT):
        subprocess.call([INIT_SCRIPT, "stop"], stdout=devnull, stderr=devnull)
    else:
        subprocess.call(["killall", "tailscaled"], stdout=devnull, stderr=devnull)
    devnull.close()

def start_service():
    conf = read_config(CONFFILE)

    enable   = conf.get("TAILSCALE_ENABLE", "off")
    authkey  = conf.get("AUTH_KEY", "")
    routes   = conf.get("ADVERTISE_ROUTES", "")
    accept_r = conf.get("ACCEPT_ROUTES", "off")
    accept_d = conf.get("ACCEPT_DNS", "off")
    snat_r   = conf.get("SNAT_SUBNET_ROUTES", "off")
    reset_f  = conf.get("RESET_ON_START", "on")

    devnull = open(os.devnull, 'w')

    if enable == "on":
        if os.path.exists(INIT_SCRIPT):
            subprocess.call([INIT_SCRIPT, "start"], stdout=devnull, stderr=devnull)
        else:
            subprocess.Popen([TSD_BIN], stdout=devnull, stderr=devnull)

        time.sleep(1)

        # Adicionada a flag --netfilter-mode=off para desabilitar gestao do iptables pelo Tailscale
        cmd = [TS_BIN, "up", "--netfilter-mode=off"]

        if authkey:
            cmd.append("--authkey=" + authkey)
        if routes:
            cmd.append("--advertise-routes=" + routes)

        cmd.append("--accept-routes=true" if accept_r == "on" else "--accept-routes=false")
        cmd.append("--accept-dns=true" if accept_d == "on" else "--accept-dns=false")
        cmd.append("--snat-subnet-routes=true" if snat_r == "on" else "--snat-subnet-routes=false")

        if reset_f == "on":
            cmd.append("--reset")

        subprocess.call(cmd, stdout=devnull, stderr=devnull)
    else:
        stop_service()

    devnull.close()

def show_status():
    try:
        proc = subprocess.Popen([TS_BIN, "status"], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
        output, _ = proc.communicate()
        print output
    except Exception as e:
        print "Error fetching status: " + str(e)

def main():
    arg = sys.argv[1] if len(sys.argv) > 1 else ""

    if arg in ["-h", "--help"]:
        print_help()
    elif arg == "--status":
        show_status()
    elif arg == "--stop":
        stop_service()
    elif arg == "--restart":
        stop_service()
        time.sleep(1)
        start_service()
    elif arg == "--start" or arg == "":
        start_service()
    else:
        print "Unknown option: %s" % arg
        print_help()
        sys.exit(1)

if __name__ == "__main__":
    main()