#!/usr/bin/env python
#
# Copyright 2009 Dan Smith <dsmith@danplanet.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

import os
import sys
import serial
import commands

from chirp import idrp, chirp_common


def open_device():
    try:
        s = serial.Serial(port="/dev/icom",
                          baudrate=idrp.IDRPx000V.BAUD_RATE,
                          timeout=0.1)
    except Exception, e:
        print "Unable to open serial port %s: %s" % ("/dev/icom", e)
        return None

    rp = idrp.IDRPx000V(s)

    return rp


def read_freq():
    rp = open_device()
    if not rp:
        return 0

    try:
        mem = rp.get_memory(0)
    except Exception, e:
        print "Unable to read memory from device: %s" % e
        return 0

    rp.pipe.close()

    return mem.freq


def _set_freq(rp):
    try:
        mem = rp.get_memory(0)
    except Exception, e:
        print "Unable to read memory from device: %s" % e
        return False

    print "\nNew frequency [%s]: " % chirp_common.format_freq(mem.freq),
    input = sys.stdin.readline().strip()

    if not input:
        print "Frequency unchanged"
        return False

    try:
        mem.freq = chirp_common.parse_freq(input)
    except Exception:
        print "Invalid entry `%s'" % input
        return False

    try:
        rp.set_memory(mem)
    except Exception, e:
        print "Failed to set frequency to %s: %s" % \
            (chirp_common.format_freq(mem.freq), e)
        return False

    print "Successfully set frequency to %s" % \
        chirp_common.format_freq(mem.freq)
    return True


def set_freq():
    rp = open_device()
    if not rp:
        return

    try:
        res = _set_freq(rp)
    except Exception, e:
        print "Unknown error while setting frequency: %s" % e
        res = False

    rp.pipe.close()
    return res


def main_menu():
    print "Looking for a repeater...",
    sys.stdout.flush()
    freq = read_freq()
    if not freq:
        return 1
    print "\r                                          \r",

    cmd = ""
    while cmd != "3":
        print """
KK7DS ID-RP* Frequency Tool
Current Setting: %s
--------------------------------
1. Set repeater frequency
2. Re-read current frequency
3. Quit
--------------------------------
> """ % chirp_common.format_freq(freq),

        cmd = sys.stdin.readline().strip()

        if cmd == "1":
            if set_freq():
                freq = read_freq()
        elif cmd == "2":
            freq = read_freq()
        elif cmd != "3":
            print "Invalid entry"

    return 0


if __name__ == "__main__":
    if os.path.exists("tools/icomsio.sh"):
        path = "tools/icomsio.sh"
    else:
        path = "icomsio.sh"
    r = os.system(path)
    if r:
        sys.exit(r)

    if not os.geteuid() == 0:
        print "Sorry, this must be run as root"
        sys.exit(1)
    sys.exit(main_menu())
