#!/usr/bin/env python2.7
# -*- coding: utf-8 -*-

import sys
import subprocess

def restart():
    """Executes ddns-clients service restart"""
    cmd = ["/etc/init.d/ddns-clients", "restart"]
    try:
        subprocess.check_call(cmd)
    except subprocess.CalledProcessError as e:
        sys.exit(e.returncode)
    except OSError:
        sys.stderr.write("Error: Executable '%s' not found.\n" % cmd[0])
        sys.exit(1)

def force():
    """Executes forced update command ddnsd force"""
    cmd = ["/sbin/ddnsd", "force"]
    try:
        subprocess.check_call(cmd)
    except subprocess.CalledProcessError as e:
        sys.exit(e.returncode)
    except OSError:
        sys.stderr.write("Error: Executable '%s' not found.\n" % cmd[0])
        sys.exit(1)

def main():
    if len(sys.argv) < 2:
        sys.stderr.write("Usage: /usr/local/bin/ddns-clients {restart|force}\n")
        sys.exit(1)

    action = sys.argv[1].lower()

    if action == "restart":
        restart()
    elif action == "force":
        force()
    else:
        sys.stderr.write("Invalid action: '%s'. Use 'restart' or 'force'.\n" % action)
        sys.exit(1)

if __name__ == "__main__":
    main()