#! /usr/bin/python3
#
# Copyright (c) 2020, AT&T Intellectual Property
# All rights reserved.
#
# SPDX-License-Identifier: LGPL-2.1-only

import subprocess
import sys
import re

def usage():
    print("usage: packet-memory-retune {info | now | next_reboot | load-next-reboot <file>}")
    sys.exit(1)

def retune():
    # Timeout in millisecs, 600000=10mins
    cmd = "/opt/vyatta/bin/vplsh -l -t 600000 -c  'fal plugin_ret bcm shell DDRPhyTune 0xff Action=3' > /dev/null 2>&1"
    result = subprocess.call(cmd, shell=True)
    if result:
        print ("Failed to tune DRAM")
        sys.exit(1)
    return 0

def save_tune():
    cmd = [ "/lib/vplane/dpp_dram_save_tune", "--platform",
            platform, "--overwrite" ]
    result = subprocess.call(cmd)
    if result:
        print ("Failed to tune DRAM")
        sys.exit(1)
    return 0

def clear_tune():
    cmd = [ "/lib/vplane/dpp_dram_save_tune", "--platform",
            platform, "--clear" ]
    result = subprocess.call(cmd)
    if result:
        print ("Failed to tune DRAM")
        sys.exit(1)
    return 0

def verify_file(file):
    try:
        print("verifying file {}\n".format(file))
        exit_seen = 0
        with open(file) as f:
            for line in f:
                # Allow comments
                # All other lines must start with:
                # "config add combo28_tune_"
                # last line with text must be 'exit'
                if re.match("\s*#", line):
                    pass
                elif re.match("\s*config\s+add\s+combo28_tune", line):
                    pass
                elif re.match("\s*exit", line):
                    if exit_seen:
                        print("File has multiple 'exit' lines\n")
                        sys.exit(1)
                    exit_seen = 1
                else:
                    print ("Invalid line: {}".format(line))
                    sys.exit(1)

        if exit_seen == 0:
            print("File has no 'exit' line\n")
            sys.exit(1)

    except Exception as e:
        print("Could not verify file format\n")
        sys.exit(1)

def load_next_reboot(file):
    verify_file(file)
    cmd = [ "/lib/vplane/dpp_dram_save_tune", "--platform",
            platform, "--load-next-reboot", file ]
    result = subprocess.call(cmd)
    if result:
        print ("Failed to load file for next reboot\n")
        sys.exit(1)
    return 0

def show_tune_info():
    cmd = [ "/lib/vplane/dpp_dram_save_tune", "--platform",
            platform, "--info" ]
    result = subprocess.call(cmd)
    if result:
        print ("Could not find dram tune info")
        sys.exit(1)
    return 0

def main():
    if sys.argv[2] == 'now':
        retune()
        save_tune()
    elif sys.argv[2] == 'info':
        show_tune_info()
    elif sys.argv[2] == 'next-reboot':
        clear_tune()
    elif sys.argv[2] == 'load-next-reboot':
        load_next_reboot(sys.argv[3])
    sys.exit(0)

if __name__ == '__main__':

    global platform
    platform = sys.argv[1]

    if len(sys.argv) != 3 and len(sys.argv) != 4:
        usage()
    if len(sys.argv) == 3 and \
       sys.argv[2] != 'now' and \
       sys.argv[2] != 'next-reboot' and \
       sys.argv[2] != 'info':
        usage()
    if len(sys.argv) == 4 and sys.argv[2] != 'load-next-reboot':
        usage()
    main()
