#!/usr/bin/env python3

# 输入文件路径（每行一个表名）
input_file = 'tables.txt'

# 输出的三个脚本文件
create_file = 'snapshot_create.sh'
export_file = 'snapshot_export.sh'
restore_file = 'snapshot_restore.sh'
count_file = 'count.sh'

# 目标 HDFS 地址
hdfs_target = 'hdfs://10.86.5.94:8020/hbase/'

# 打开三个输出文件进行写入
with open(input_file, 'r') as fin:
    with open(create_file, 'w') as f_create, \
         open(export_file, 'w') as f_export, \
         open(restore_file, 'w') as f_restore, \
         open(count_file, 'w') as f_count  :

        # 添加 shebang 行
        f_create.write('#!/bin/bash\n')
        f_export.write('#!/bin/bash\n')
        f_restore.write('#!/bin/bash\n')

        for line in fin:
            table_name = line.strip()
            if not table_name or table_name.startswith('#'):
                continue  # 忽略空行和注释行

            snapshot_name = f"{table_name}_snapshot"

            # 命令1：创建快照
            del_cmd = f"delete_snapshot '{snapshot_name}'"
            f_create.write(del_cmd + '\n')
            create_cmd = f"snapshot '{table_name}','{snapshot_name}'"
            f_create.write(create_cmd + '\n')

            # 命令2：导出快照
            export_cmd = (
                f"hbase org.apache.hadoop.hbase.snapshot.ExportSnapshot "
                f"-snapshot {snapshot_name} -copy-to {hdfs_target}  -overwrite"
            )
            f_export.write(export_cmd + '\n')

            # 命令3：恢复快照（disable -> restore -> enable）
            restore_shell = (
                f"echo \"disable '{table_name}'; restore_snapshot '{snapshot_name}'; enable '{table_name}'\" | hbase shell -n "
            )
            f_restore.write(restore_shell + '\n')
            # 命令四：count（disable -> restore -> enable）
            count_cmd = (
                f"echo \"count '{table_name}'\" | hbase shell -n >>count.log"
            )
            f_count.write(count_cmd + '\n')


print("✅ 四个脚本已生成：")
print(f"   - {create_file}")
print(f"   - {export_file}")
print(f"   - {restore_file}")
print(f"   - {count_file}")

